<?php
/**
 * 春哥团队（www.cgtblog.com） - 春哥多端多商户万能DIY商城系统
 * Copyright © 2024 春哥技术团队 保留所有权利
 * =========================================================

 * ----------------------------------------------
 * 您只能在商业授权范围内使用，不可二次转售、分发、分享、传播
 * 任何企业和个人不得对代码以任何目的任何形式的再发布
 * =========================================================
 */

namespace app\common;
use think\facade\Db;
class Order
{
	//订单退款  1余额支付 2微信支付 3支付宝支付 4货到付款 11百度小程序 12头条小程序
	public static function refund($order,$refund_money,$reason='退款'){
		if(!$reason) $reason = '退款';
		$paytype = $order['paytypeid'];
		if(!$paytype) return ['status'=>1,'msg'=>''];
		if($refund_money == 0) return ['status'=>1,'msg'=>''];
        //代付订单退款，推给实际支付人
        //如果是代付则退回代付账号,不可以用orderid[]
        $payorder = Db::name('payorder')->where('aid',$order['aid'])->where('ordernum',$order['ordernum'])->find();
        if(strpos($order['ordernum'],'_')){ //合并支付
            $ordernum = explode('_',$order['ordernum'])[0];
            $payorder = Db::name('payorder')->where('aid',$order['aid'])->where('ordernum',$ordernum)->find();
            if($payorder['status']==1){ //是合并支付的
                $order['totalprice'] = $payorder['money'];
                $order['ordernum'] = $ordernum;
            }
        }
        if($payorder['paymid']>0){
            $payorderP = Db::name('payorder')->where('status',1)->where('pid',$payorder['id'])->find();
            $mid = $payorderP['mid'];
//            $order['platform'] = $payorderP['platform'];
            $order['ordernum'] = $payorderP['ordernum'];
            $order['totalprice'] = $payorderP['money'];
            $remark = '代付订单退款';
        }else{
            $mid = $order['mid'];
            $remark = '订单退款';
        }
		if($paytype == 1){
			$rs = \app\common\Member::addmoney($order['aid'],$mid,$refund_money,$remark.' '.$reason);
		}

		if($paytype == 2){
			$rs = \app\common\Wxpay::refund($order['aid'],$order['platform'],$order['ordernum'],$order['totalprice'],$refund_money,$reason,$order['bid'],$payorder);
		}
		if($paytype == 3){
			$rs = \app\common\Alipay::refund($order['aid'],$order['platform'],$order['ordernum'],$order['totalprice'],$refund_money,$reason,$order['bid']);
		}
		if($paytype == 4){
			$rs = ['status'=>1,'msg'=>''];
		}
		//转账汇款
        if($paytype == 5){
            $rs = ['status'=>1,'msg'=>''];
        }
		if($order['paytypeid'] == 11){ //百度小程序
			$rs = \app\common\Baidupay::refund($order['aid'],$order['mid'],$order['ordernum'],$order['paynum'],$order['totalprice'],$refund_money,$reason);
		}
		if($order['paytypeid'] == 12){ //头条小程序
			$rs = \app\common\Ttpay::refund($order['aid'],$order['ordernum'],$order['totalprice'],$refund_money,$reason);
		}
		if($order['paytypeid'] == 22){ //云收银
			$rs = \app\common\Yunpay::refund($order['aid'],$order['platform'],$order['ordernum'],$order['totalprice'],$refund_money,$reason);
		}
		if($order['paytypeid'] == 23){
			$rs = \app\common\Qmpay::refund($order['aid'],$order['platform'],$order['ordernum'],$order['totalprice'],$refund_money,$reason);
		}
		if($order['paytypeid'] == 24){
			$rs = \app\common\Qmpay::refund2($order['aid'],$order['platform'],$order['ordernum'],$order['totalprice'],$refund_money,$reason);
		}
		if($order['paytypeid'] == 51){  //paypal
			$rs = \app\custom\PayPal::refund($order['aid'],$order['platform'],$order['ordernum'],$order['totalprice'],$refund_money,$reason);
		}
        //透支额度支付
        if($paytype == 38){
            $rs = \app\common\Member::addOverdraftMoney($order['aid'],$mid,$refund_money,$remark.' '.$reason);
        }
        if($order['paytypeid'] == 60){ //视频号
            $rs = ['status'=>1,'msg'=>''];
        }
		if($order['paytypeid'] == 60){ //视频号
			$rs = ['status'=>1,'msg'=>''];
		}
		return $rs;
	}
	//订单收货
	public static function collect($order,$type='shop',$commission_mid = 0){
		$aid = $order['aid'];
		$mid = $order['mid'];
        $platformMoney = 0;
        $business_lirun = 0;
        if(getcustom('yx_jidian') && $order['bid']) {
            $jidian_set = Db::name('jidian_set')->where('aid', $aid)->where('bid', $order['bid'])->find();
            $paygive_scene = explode(',',$jidian_set['paygive_scene']);
        }
		if($type == 'shop'){
			if($order['fromwxvideo'] == 1){
				\app\common\Wxvideo::deliveryrecieve($order['id']);
			}

			if(getcustom('cefang') && $aid==2){ //定制1 订单对接 同步到策方
			    $order2 = $order;
			    $order2['status'] = 3;
				\app\custom\Cefang::api($order2);
			}

            $oglist = Db::name('shop_order_goods')->where('aid',$aid)->where('orderid',$order['id'])->select()->toArray();
            if($order['bid']!=0){//入驻商家的货款
				$totalnum = 0;
				foreach($oglist as $og){
					$totalnum += $og['num'];
				}
				
				$totalcommission = 0;
				$og_business_money = false;
				$totalmoney = 0;
				$all_cost_price = 0;
				$lirun_cost_price = 0;
				$total_cost_price = 0;
				foreach($oglist as $og){
					//if($og['iscommission']) continue;
					if($og['parent1'] && $og['parent1commission'] > 0){
						$totalcommission += $og['parent1commission'];
					}
					if($og['parent2'] && $og['parent2commission'] > 0){
						$totalcommission += $og['parent2commission'];
					}
					if($og['parent3'] && $og['parent3commission'] > 0){
						$totalcommission += $og['parent3commission'];
					}
					if(!is_null($og['business_total_money'])) {
						$og_business_money = true;
						$totalmoney += $og['business_total_money'];
					}
					if(getcustom('business_deduct_cost')){
						if(!empty($og['cost_price']) && $og['cost_price']>0){
							if($og['cost_price']<=$og['sell_price']){
								$all_cost_price += $og['cost_price'];
							}else{
								$all_cost_price += $og['sell_price'];
							}
						}
					}
                    if(getcustom('business_agent')){
                        if(!empty($og['cost_price']) && $og['cost_price']>0){
                            $lirun_cost_price += $og['cost_price'];
                        }
                    }
                    if(getcustom('business_fee_type')){
                        if(!empty($og['cost_price']) && $og['cost_price']>0){
                            $total_cost_price += $og['cost_price'];
                        }
                    }
				}
				$binfo = Db::name('business')->where('aid',$aid)->where('id',$order['bid'])->find();
				$bset = Db::name('business_sysset')->where('aid',$aid)->find();
				if($bset['commission_kouchu'] == 0){ //不扣除佣金
					$totalcommission = 0;
				}
                if(getcustom('business_agent')){                    
                    $business_lirun = $order['totalprice']-$order['refund_money']-$lirun_cost_price;
                }
				//商品独立费率
				if($og_business_money) {
                    $totalmoney = $totalmoney + $order['freight_price'] - $totalcommission - $order['refund_money'];
                    $platformMoney = $order['totalprice']-$totalmoney - $order['refund_money'];
				} else {
					$scoredkmoney = $order['scoredk_money'] ?? 0;
					if($bset['scoredk_kouchu'] == 0){ //扣除积分抵扣
						$scoredkmoney = 0;
					}

					$leveldkmoney = $order['leveldk_money'] ?? 0;
					if($bset['leveldk_kouchu'] == 0){ //扣除积分抵扣
						$leveldkmoney = 0;
					}

					$totalmoney = $order['product_price'] + $order['freight_price'] - $order['coupon_money'] - $order['manjia_money'] - $order['discount_money_admin'] - $order['refund_money'] - $totalcommission - $scoredkmoney - $leveldkmoney;
					if($totalmoney > 0){
						if(getcustom('business_deduct_cost')){
                        	if($binfo && $binfo['deduct_cost'] == 1){
	                        	//扣除成本
                                $platformMoney = ($totalmoney-$all_cost_price)*$binfo['feepercent']/100;
			                }else{
                                $platformMoney = $totalmoney * $binfo['feepercent'] * 0.01;
			                }                            
		                }else{
                            $platformMoney = $totalmoney * $binfo['feepercent'] * 0.01;                                                                                
		                }
                        if(getcustom('business_fee_type')){
                            if($bset['business_fee_type'] == 1){
                                $platformMoney = ($order['totalprice']-$order['freight_price']) * $binfo['feepercent'] * 0.01;
                            }elseif($bset['business_fee_type'] == 2){
                                $platformMoney = $total_cost_price * $binfo['feepercent'] * 0.01;
                            }
                        } 
                        $totalmoney = $totalmoney - $platformMoney;
					}
				}

				if($order['paytypeid']==4){
					$totalmoney = $totalmoney - $order['totalprice'];
				}

				$isbusinesspay = Db::name('payorder')->where('aid',$aid)->where('ordernum',$order['ordernum'])->value('isbusinesspay');
				if(!$isbusinesspay){
					if($totalmoney < 0){
						$bmoney = Db::name('business')->where('aid',$aid)->where('id',$order['bid'])->value('money');
						if($bmoney + $totalmoney < 0){
							return ['status'=>0,'msg'=>'操作失败,商家余额不足'];
						}
					}
					//商家货款
					\app\common\Business::addmoney($aid,$order['bid'],$totalmoney,'货款，订单号：'.$order['ordernum'],true,$type,$order['ordernum'],['platformMoney'=>$platformMoney,'business_lirun'=>$business_lirun]);
				}else{
					//商家推荐分成
					if($totalmoney > 0){
						if(getcustom('business_agent')){
							\app\common\Business::addparentcommission2($aid,$order['bid'],$totalmoney,$platformMoney,$business_lirun);
						}else{
							\app\common\Business::addparentcommission($aid,$order['bid'],$totalmoney);
						}
					}
				}
                //店铺加销量
                Db::name('business')->where('aid',$aid)->where('id',$order['bid'])->inc('sales',$totalnum)->update();
                //Db::name('shop_order_goods')->where('aid',$aid)->where('orderid',$order['id'])->update(['iscommission' => 1]);
                if(getcustom('yx_jidian')){
                    //集点
                    if($jidian_set && in_array('shop',$paygive_scene) && $jidian_set['status'] == 1 && time() >= $jidian_set['starttime'] && time() <= $jidian_set['endtime']){
                        //执行时此笔订单还没收货
                        \app\common\System::getOrderNumFromJidian($aid,$order['bid'],$jidian_set,$order['mid'],1,true);
                    }
                }

                if(getcustom('pay_yuanbao')){
                    //元宝支付
                    //查询商家
                    $business = Db::name('business')->where('id',$order['bid'])->field('mid')->find();
                    if($business && $business['mid']>0){
                        //查询用户是否存在
                        $count_member = Db::name('member')
                            ->where('id',$business['mid'])
                            ->count();
                        if($count_member){
                            //给商家用户发元宝
                            \app\common\Member::addyuanbao($order['aid'],$business['mid'],$order['total_yuanbao'],'订单:'.$order['ordernum'].'完成发放');
                        }
                    }
                }
				if(getcustom('business_moneypay') && in_array($order['paytypeid'],[2,3,12,13])){ //多商户设置的消费送积分
					$bset = Db::name('business_sysset')->where('aid',$aid)->find();
					$givescore = floor($order['totalprice'] / $bset['scorein_money']) * $bset['scorein_score'];
					if($givescore > 0){
						\app\common\Member::addscore($aid,$order['mid'],$givescore,'消费送'.t('积分'));
					}
				}

				if(getcustom('business_canuseplatcoupon') && $order['coupon_money'] > 0 && $order['coupon_rid'] > 0){
					$couponrecord = Db::name('coupon_record')->where('id',$order['coupon_rid'])->find();
					if($couponrecord && $couponrecord['bid'] == 0){
						$businessuserecord = [];
						$businessuserecord['aid'] = $order['aid'];
						$businessuserecord['bid'] = $order['bid'];
						$businessuserecord['mid'] = $order['mid'];
						$businessuserecord['ordertype'] = $type;
						$businessuserecord['orderid'] = $order['id'];
						$businessuserecord['couponrid'] = $order['coupon_rid'];
						$businessuserecord['couponid'] = $couponrecord['couponid'];
						$businessuserecord['couponname'] = $couponrecord['couponname'];
						$businessuserecord['couponmoney'] = $couponrecord['money'];
						$businessuserecord['decmoney'] = $order['coupon_money'];
						$businessuserecord['status'] = 1;
						$businessuserecord['createtime'] = time();
						Db::name('coupon_businessuserecord')->insert($businessuserecord);
						Db::name('business')->where('id',$order['bid'])->inc('couponmoney',$order['coupon_money'])->update();
					}
				}
            }
            //赠积分
            if($order['givescore'] > 0){
				if($order['bid'] > 0){
					\app\common\Business::addmemberscore($aid,$order['bid'],$order['mid'],$order['givescore'],'购买产品赠送'.t('积分'));
				}else{
					\app\common\Member::addscore($aid,$order['mid'],$order['givescore'],'购买产品赠送'.t('积分'));
				}
            }
            if(getcustom('product_givetongzheng')){
                if($order['givetongzheng']>0){
                    $release_bili = Db::name('admin_set')->where('aid',$order['aid'])->value('tongzheng_release_bili');
                    $tz_log = [];
                    $tz_log['aid'] = $order['aid'];
                    $tz_log['mid'] = $order['mid'];
                    $tz_log['orderid'] = $order['id'];
                    $tz_log['tongzheng'] = $order['givetongzheng'];
                    $tz_log['release_bili'] = $release_bili;
                    $tz_log['remain'] = $order['givetongzheng'];
                    $tz_log['createtime'] = time();
                    Db::name('tongzheng_order_log')->insert($tz_log);
                }
            }

            if(getcustom('everyday_hongbao')) {
                $totalHongbao = 0;
                foreach($oglist as $og){
                    if($og['ishongbao'] || $og['hongbaoEdu'] <= 0) continue;
                    \app\common\Member::addHongbaoEverydayEdu($aid,$order['mid'],$og['hongbaoEdu'], '购买增加红包额度', $og['id']);
                }
                Db::name('shop_order_goods')->where('aid',$aid)->where('orderid',$order['id'])->update(['ishongbao' => 1]);
            }

            if(getcustom('discount_code_zhongchuang')){
                if($order['discount_code_zc']){
                    //中创推送订单数据
                    $postzcog = [];
                    foreach($oglist as $og){
                        $postzcog[] = [
                            'proid'=>$og['proid'],
                            'name'=>$og['name'],
                            'pic'=>$og['pic'],
                            'procode'=>$og['procode'],
                            'ggid'=>$og['ggid'],
                            'ggname'=>$og['ggname'],
                            'num'=>$og['num'],
                            'sell_price'=>$og['sell_price'],
                            'totalprice'=>$og['totalprice'],
                        ];
                    }
                    $postzc =[
                        'invitecode' => $order['discount_code_zc'],
                        'order'=> [
                            'ordernum' => $order['ordernum'],
                            'totalprice' => $order['totalprice'],
                            'product_price' => $order['product_price'],
                            'freight_price' => $order['freight_price'],
                            'scoredk_money' => $order['scoredk_money'],
                            'leveldk_money' => $order['leveldk_money'],
                            'manjian_money' => $order['manjian_money'],
                            'coupon_money' => $order['coupon_money'],
                            'discount_money_admin' => $order['discount_money_admin'],
                            'cuxiao_money' => $order['cuxiao_money'],
                            'createtime' => $order['createtime'],
                            'linkman' => $order['linkman'],
                            'tel' => $order['tel'],
                            'area' => $order['area'],
                            'address' => $order['address'],
                            'paytime' => $order['paytime'],
                            'collect_time' => $order['collect_time'],
                        ],
                        'orderGoods'=> $postzcog
                    ];
                    $url ='https://zckl.zhoming.top/imcore/api/mall/getUserInfo';
                    $res = curl_post($url,jsonEncode($postzc),0,array('Content-Type: application/json'));
                    $res = json_decode($res,true);
                    \think\facade\Log::write('中创rs:'.jsonEncode($res));
                }
            }            
			//购物返现
            $bid = $order['bid'];
            if(getcustom('cashback_yongjin')){
                //定制总后台添加多商户商品
                $bid = 0;
            }
			$cashbacklist = Db::name('cashback')
				->where('aid',$aid)
				->where('bid',$bid)
				->where('starttime','<',$order['paytime'])
				->where('endtime','>',$order['paytime'])
				->order('sort desc')->select()->toArray();

			//查询购买用户
			$member = Db::name('member')
				->where('id',$order['mid'])
				//->field('levelid')
				->find();

			if($oglist && $member && $cashbacklist){
				foreach($oglist as $og){
					$product = Db::name('shop_product')
						->where('id',$og['proid'])
						->field('id,cid')
						->find();

					if($product){

						foreach($cashbacklist as $v){

							$gettj = explode(',',$v['gettj']);
							if(!in_array('-1',$gettj) && !in_array($member['levelid'],$gettj)){ //不是所有人
								continue;
							}

							if($v['fwtype']>=3){
								//其他类型不适应
								continue;
							}

							if($v['fwtype']==2){//指定商品可用
								$productids = explode(',',$v['productids']);
								if(!in_array($product['id'],$productids)){
									continue;
								}
							}

							if($v['fwtype']==1){//指定类目可用
								$categoryids = explode(',',$v['categoryids']);
								$cids = explode(',',$product['cid']);
								$clist = Db::name('shop_category')->where('pid','in',$categoryids)->select()->toArray();
								foreach($clist as $vc){
									$categoryids[] = $vc['id'];
									$cate2 = Db::name('shop_category')->where('pid',$vc['id'])->find();
									$categoryids[] = $cate2['id'];
								}
								if(!array_intersect($cids,$categoryids)){
									continue;
								}
							}

							//如果返现利率大于0
							if($v['back_ratio']>0){
								//计算返现
								$back_price = $v['back_ratio']*$og['real_totalprice']/100;
                                if(getcustom('money_dec')){
                                    //如果是余额抵扣，则要加上余额部分
                                    if($og['dec_money'] && $og['dec_money'] >0){
                                        $back_price = $v['back_ratio']*($og['real_totalprice']+$og['dec_money'])/100;
                                    }
                                }

								//返现类型 1、余额 2、佣金 3、积分
								if($v['back_type'] == 1 || $v['back_type']== 2){
									$back_price = round($back_price,2);
								}

								if($v['back_type'] == 3){

									$back_price = round($back_price);
								}

                                $send_status = 0;//发放状态
                                if(getcustom('yx_cashback_time')){
                                    //如果返回类型为每天返回
                                    if($v['return_type'] == 1){
                                        $send_status = 1;//发放状态
                                    }
                                }
                                //记录参与的会员
                                $cashback_member_check = Db::name('cashback_member')->where('aid',$order['aid'])->where('mid',$order['mid'])->where(['cashback_id'=>$v['id'],'pro_id'=>$og['proid']])->find();
                                if(!$cashback_member_check){
                                    $cashback_member = [];                                            
                                    $cashback_member['aid'] = $order['aid'];
                                    $cashback_member['mid'] = $order['mid'];
                                    $cashback_member['cashback_id'] = $v['id'];
                                    $cashback_member['pro_id'] = $og['proid'];
                                    $cashback_member['pro_num'] = $og['num'];
                                    $cashback_member['cashback_money_max']     = $v['goods_multiple_max'] > 0 ? $og['sell_price'] * $v['goods_multiple_max'] * $og['num']:0;
                                    //$cashback_member['cashback_money']     = $back_price;
                                    $cashback_member['back_type']          = $v['back_type'];
                                    $cashback_member['create_time'] = time();
                                    $insert = Db::name('cashback_member')->insert($cashback_member);
                                    $cashback_member_check = Db::name('cashback_member')->where('aid',$order['aid'])->where('mid',$order['mid'])->where(['cashback_id'=>$v['id'],'pro_id'=>$og['proid']])->find();
                                }else{
                                    Db::name('cashback_member')->where('id',$cashback_member_check['id'])->inc('pro_num',$og['num'])->update();
                                    $cashback_money_max     = $v['goods_multiple_max'] > 0 ? $og['sell_price'] * $v['goods_multiple_max']* $og['num']:0;
                                    $cashback_member['cashback_money_max']  = $cashback_member_check['cashback_money_max'] + $cashback_money_max;
                                    Db::name('cashback_member')->where('id',$cashback_member_check['id'])->update($cashback_member);
                                }

                                //开启限额
                                $cashback_max = 0;
                                if(getcustom('cashback_max')){
                                    $cashback_max = 1;
                                }
                                //开启选择受益人
                                $cashback_receiver = 0;
                                if(getcustom('cashback_receiver')){
                                    $cashback_receiver = 1;
                                }

                                if(!$send_status){                                    

                                    //受益人限额仅限单个商品可用
                                    if($cashback_receiver || $cashback_max){
                    
                                        if($back_price){                                        
                                            //判定受益人的方式1
                                            if($v['receiver_type'] == 1){
                                                //判定是否限额
                                                if($v['back_type'] == 1 ){
                                                    $cashback_num = $cashback_member_check['cashback_money'];
                                                }
                                                if($v['back_type'] == 2){        
                                                    $cashback_num = $cashback_member_check['commission'];
                                                }
                                                if($v['back_type'] == 3){
                                                    $cashback_num = $cashback_member_check['score'];
                                                }        
                                                if($v['goods_multiple_max'] > 0 &&  $cashback_member_check['cashback_money_max'] > $cashback_num){
                                                    //最大可追加金额
                                                    $cashback_money_max = $cashback_member_check['cashback_money_max'] - $cashback_num;
                                                    if($cashback_money_max < $back_price){
                                                        $back_price = $cashback_money_max;
                                                    }                                                    
                                                    
                                                }
                                            }elseif($v['receiver_type'] ==2){//参与活动的人
                                                //查询参与活动的所有人发放佣金
                                               $res_code = self::cashbackMemerDo($order['aid'],$order['mid'],$v,$og,$back_price);
                                                $back_price = 0;
                                            }
                                        }
    					            }
    								if($back_price>0){
    									if($v['back_type'] == 1 ){

    										\app\common\Member::addmoney($aid,$order['mid'],$back_price,$v['name']);
                                            //累计到参与人统计表
                                            Db::name('cashback_member')->where('id',$cashback_member_check['id'])->inc('cashback_money',$back_price)->update();
    									}
    									if($v['back_type'] == 2){

    										\app\common\Member::addcommission($aid,$order['mid'],$order['mid'],$back_price,$v['name']);
                                            //累计到参与人统计表
                                            Db::name('cashback_member')->where('id',$cashback_member_check['id'])->inc('commission',$back_price)->update();
    									}
    									if($v['back_type'] == 3){
    										\app\common\Member::addscore($aid,$order['mid'],$back_price,$v['name']);
                                            //累计到参与人统计表
                                            Db::name('cashback_member')->where('id',$cashback_member_check['id'])->inc('score',$back_price)->update();
    									}
                                        if(getcustom('yx_cashback_time')){
                                            //直接发放
                                            \app\custom\OrderCustom::deal_first_cashback($aid,$order['mid'],$back_price,$og,$v);
                                        }
                                        //写入发放日志
                                        \app\custom\OrderCustom::cashbackMemerDoLog($order['aid'],$order['mid'],$v,$og,$back_price);
    								}
                                }else{
                                    if(getcustom('yx_cashback_time')){
                                        if($send_status && $back_price>0){
                                            //处理自定义第一次发放
                                            //处理受益人是参与人
                                            if($cashback_receiver == 1 && $v['receiver_type'] ==2){
                                                //查询参与活动的所有人发放佣金
                                                $res_code = self::cashbackMemerDo($order['aid'],$order['mid'],$v,$og,$back_price,1);
                                            }else{
                                                \app\custom\OrderCustom::deal_first_cashback($aid,$order['mid'],$back_price,$og,$v,1);
                                            }
                                            
                                        }
                                    }
                                }
							}

						}
					}
				}
			}
            if(getcustom('product_bonus_pool')){
                if($oglist && $member){
                    foreach($oglist as $og){
                        $field='id,cid';
                        $field .=',bonus_pool_ratio,bonus_pool_num,bonus_pool_releasetj';
                        $product = Db::name('shop_product')
                            ->where('id',$og['proid'])
                            ->field($field)
                            ->find();
                        if($product && $product['bonus_pool_ratio']){
                            //加入奖金池
                            for($i=0;$i < $product['bonus_pool_num'];$i++){
                                $pool_money = $product['bonus_pool_ratio']/100 *$og['totalprice'];
                                $money = dd_money_format($pool_money / $product['bonus_pool_num']);
                                if($money > 0){
                                    $pool_data = [
                                        'aid' => $og['aid'],
                                        'bid' => $og['bid'],
                                        'money' => $money,
                                        'ogid' => $og['id'],
                                        'createtime' => time()
                                    ];
                                    Db::name('bonus_pool')->insert($pool_data); 
                                }
                               
                            }
                        }

                    }
                }
                if($oglist){
                    //奖金池 记录 发放
                    foreach ($oglist as $og){
                        $recordlist = Db::name('member_bonus_pool_record')->where('aid',$og['aid'])->where('ogid',$og['id'])->select()->toArray();
                      
                        foreach ($recordlist as $rk=>$rv){
                            $member = Db::name('member')->where('id',$rv['mid'])->find();
                            $bonus_pool_money = dd_money_format($member['bonus_pool_money'] + $rv['commission']);
                            //增加log
                            $log = [
                                'aid' =>$rv['aid'],
                                'mid' =>$rv['mid'],
                                'frommid' => $og['mid'],
                                'commission' => $rv['commission'],
                                'after' => $bonus_pool_money,
                                'createtime' => time(),
                                'remark' => $rv['remark']
                            ];
                            
                            Db::name('member_bonus_pool_log') ->insert($log);
                           
                            Db::name('member')->where('id',$rv['mid'])->update(['bonus_pool_money' => $bonus_pool_money]);
                            Db::name('member_bonus_pool_record')->where('id',$rv['id'])->update(['status' => 1,'endtime' => time()]);
                        }
                    }
                   
                }
            }
			if(getcustom('invite_free')){
				if($order['is_free'] ||$member['pid']>0){
					//处理上级邀请免单及退回自己免单余额
					\app\custom\InviteFree::deal_free($member,$order);
				}
			}

			if(getcustom('yx_invite_cashback')){
				//邀请返现
				if($order && $oglist && $member){
					\app\custom\OrderCustom::deal_invitecashback2($aid,$order,$oglist,$member);
				}
			}

			//恢复会员等级
			if(getcustom('member_level_down_commission') && $member['isauto_down']==1){
				if($member['up_levelid']>0){
					$level =   Db::name('member_level')->field('id,recovery_level_proid')->where('aid',$aid)->where('id',$member['up_levelid'])->find();
					$proids = [];
					$isrecovery=false;
					$recovery_level_proid = explode(',',$level['recovery_level_proid']);
					foreach ($oglist as $og){
						if(in_array($og['proid'],$recovery_level_proid)){
							$isrecovery = true;
							break;
						}
					}
					if($isrecovery){
						\app\Common\member::recovery_level($aid,$member);
					}
				}
			}

			//增加购买次数 购买金额if(getcustom('member_tag'))
            Db::name('member')->where('aid',$aid)->where('id',$mid)->inc('buynum',1)->update();
            Db::name('member')->where('aid',$aid)->where('id',$mid)->inc('buymoney',$order['totalprice'])->update();
            //支付宝小程序交易组件订单状态同步
            if($order['platform']=='alipay' && $order['paytypeid'] == 3){
                $ordernum = $order['ordernum'];
                if(strpos($ordernum, '_')!==false){
                    $ordernum = explode('-',$ordernum)[0];
                }
                if(getcustom('alipay_plugin_trade') && $order['alipay_component_orderid']){
                    $pluginResult = \app\common\Alipay::pluginOrderConfirm($aid,$mid,$ordernum);
                }
            }
			if($order['platform'] == 'toutiao'){
				\app\common\Ttpay::pushorder($aid,$order['ordernum'],4);
			}
            if(getcustom('yx_team_yeji_manage')){
                self::teamYejiManage($aid,$member);
            }
            if(getcustom('yx_queue_free')){
                \app\custom\QueueFree::join($order,$type);
            }
            if(getcustom('fenhong_jiaquan_bylevel')){
                //份数累加到会员
                \app\common\Fenhong::updateJiaquanCopies2member($order['id']);
            }
            $score_weishu = 0;
            if(getcustom('score_weishu')){
                $score_weishu = Db::name('admin_set')->where('aid',$aid)->value('score_weishu');
                $score_weishu = $score_weishu?$score_weishu:0;
            }
            if(getcustom('reward_business_score')){
                $reward_score = dd_money_format($order['reward_business_score'],$score_weishu);
                $uinfo = Db::name('admin_user')->where('aid',$aid)->where('bid',$og['bid'])->where('isadmin',1)->find();
                if($reward_score>0 && $uinfo['mid']){
                    \app\common\Member::addscore($aid,$uinfo['mid'],$reward_score,'店长奖励');
                }
            }
			
			if(getcustom('commission_withdraw_freeze')){
				$set = Db::name('admin_set')->field('jiedong_condtion,buy_proid,buypro_num')->where('aid',$aid)->find();
				if(in_array('1',explode(',',$set['jiedong_condtion']))){
					$isjiedong = false;
					foreach ($oglist as $og){
						if($og['proid']==$set['buy_proid']){
							if($og['num']>=$set['buypro_num']){
								$isjiedong = true;
							}
						}
					}
					if($isjiedong){
						Db::name('member')->where('id',$order['mid'])->update(['iscomwithdraw_freeze'=>0]);
					}
				}
			}
        }elseif($type=='collage'){
			if($order['bid']!=0){//入驻商家的货款

				$totalmoney = 0;
				$binfo = Db::name('business')->where('aid',$aid)->where('id',$order['bid'])->find();
				$bset = Db::name('business_sysset')->where('aid',$aid)->find();

                if(getcustom('business_agent')){
                    $lirun_cost_price = 0;
                    if($order['cost_price']>0){
                        $lirun_cost_price = $order['cost_price'];                           
                    }                    
                    $business_lirun = $order['totalprice']-$lirun_cost_price;
                }

				if(!is_null($order['business_total_money'])) {
					$leveldkmoney = $order['leveldk_money'] ?? 0;
					if($bset['leveldk_kouchu'] == 0){ //扣除会员抵扣
						$leveldkmoney = 0;
					}
					$totalmoney = $order['business_total_money'] - $leveldkmoney;
                    $platformMoney = $order['totalprice']-$totalmoney - $order['refund_money'];
				} else {
					$scoredkmoney = $order['scoredk_money'] ?? 0;
					if($bset['scoredk_kouchu'] == 0){ //扣除积分抵扣
						$scoredkmoney = 0;
					}
					$leveldkmoney = $order['leveldk_money'] ?? 0;
					if($bset['leveldk_kouchu'] == 0){ //扣除积分抵扣
						$leveldkmoney = 0;
					}

					$totalmoney = $order['product_price'] + $order['freight_price'] - $order['coupon_money'] - $order['leader_money'] - $scoredkmoney - $leveldkmoney;
					if($totalmoney > 0){
						if(getcustom('business_deduct_cost')){
                        	if($binfo && $binfo['deduct_cost'] == 1 && $order['cost_price']>0){
                        		if($order['cost_price']<=$order['sell_price']){
									$all_cost_price = $order['cost_price'];
								}else{
									$all_cost_price = $order['sell_price'];
								}
	                        	//扣除成本
                                $platformMoney = ($totalmoney-$all_cost_price)*$binfo['feepercent']/100;
			                }else{
                                $platformMoney = $totalmoney * $binfo['feepercent'] * 0.01;
			                }                            
		                }else{
                            $platformMoney = $totalmoney * $binfo['feepercent'] * 0.01;
		                }

                        if(getcustom('business_fee_type')){
                            if($bset['business_fee_type'] == 1){
                                $platformMoney = ($order['totalprice']-$order['freight_price']) * $binfo['feepercent'] * 0.01;
                            }elseif($bset['business_fee_type'] == 2){
                                $platformMoney = $order['cost_price'] * $binfo['feepercent'] * 0.01;
                            }
                        } 
                        $totalmoney = $totalmoney - $platformMoney;
					}
				}

				if($order['paytypeid']==4){
					$totalmoney = $totalmoney - $order['totalprice'];
				}

				$isbusinesspay = Db::name('payorder')->where('aid',$aid)->where('ordernum',$order['ordernum'])->value('isbusinesspay');
				if(!$isbusinesspay){
					if($totalmoney < 0){
						$bmoney = Db::name('business')->where('aid',$aid)->where('id',$order['bid'])->value('money');
						if($bmoney + $totalmoney < 0){
							return ['status'=>0,'msg'=>'操作失败,商家余额不足'];
						}
					}
					\app\common\Business::addmoney($aid,$order['bid'],$totalmoney,'货款，拼团订单号：'.$order['ordernum'],true,$type,$order['ordernum'],['platformMoney'=>$platformMoney,'business_lirun'=>$business_lirun]);
				}else{
					//商家推荐分成
					if($totalmoney > 0){
						if(getcustom('business_agent')){
							\app\common\Business::addparentcommission2($aid,$order['bid'],$totalmoney,$platformMoney,$business_lirun);
						}else{
							\app\common\Business::addparentcommission($aid,$order['bid'],$totalmoney);
						}
					}
				}
				//店铺加销量
				Db::name('business')->where('aid',$aid)->where('id',$order['bid'])->inc('sales',$order['num'])->update();

				if(getcustom('business_canuseplatcoupon') && $order['coupon_money'] > 0 && $order['coupon_rid'] > 0){
					$couponrecord = Db::name('coupon_record')->where('id',$order['coupon_rid'])->find();
					if($couponrecord && $couponrecord['bid'] == 0){
						$businessuserecord = [];
						$businessuserecord['aid'] = $order['aid'];
						$businessuserecord['bid'] = $order['bid'];
						$businessuserecord['mid'] = $order['mid'];
						$businessuserecord['ordertype'] = $type;
						$businessuserecord['orderid'] = $order['id'];
						$businessuserecord['couponrid'] = $order['coupon_rid'];
						$businessuserecord['couponid'] = $couponrecord['couponid'];
						$businessuserecord['couponname'] = $couponrecord['couponname'];
						$businessuserecord['couponmoney'] = $couponrecord['money'];
						$businessuserecord['decmoney'] = $order['coupon_money'];
						$businessuserecord['status'] = 1;
						$businessuserecord['createtime'] = time();
						Db::name('coupon_businessuserecord')->insert($businessuserecord);
						Db::name('business')->where('id',$order['bid'])->inc('couponmoney',$order['coupon_money'])->update();
					}
				}
			}

			if(getcustom('yx_cashback_collage')){
				//处理返现
				\app\custom\OrderCustom::deal_collagecashback($aid,$order);
			}

			if(getcustom('collage_givescore_time')){
				//赠积分
	            if($order['givescore1'] > 0){
					\app\common\Member::addscore($aid,$order['mid'],$order['givescore1'],'购买拼团商品赠送'.t('积分'));
	            }
            }
		}elseif($type=='cycle'){
            if($order['bid']!=0){//入驻商家的货款
                
                $totalmoney = 0;
                $binfo = Db::name('business')->where('aid',$aid)->where('id',$order['bid'])->find();
                $bset = Db::name('business_sysset')->where('aid',$aid)->find();

                if(getcustom('business_agent')){
                    $lirun_cost_price = 0;
                    if($order['cost_price']>0){
                        $lirun_cost_price = $order['cost_price'];                           
                    }                    
                    $business_lirun = $order['totalprice']-$lirun_cost_price;
                }

				if(!is_null($order['business_total_money'])) {
					$leveldkmoney = $order['leveldk_money'] ?? 0;
					if($bset['leveldk_kouchu'] == 0){ //扣除会员抵扣
						$leveldkmoney = 0;
					}
					$totalmoney = $order['business_total_money'] - $leveldkmoney;
                    $platformMoney = $order['totalprice']-$totalmoney - $order['refund_money'];
				} else {

					$scoredkmoney = $order['scoredk_money'] ?? 0;
					if($bset['scoredk_kouchu'] == 0){ //扣除积分抵扣
						$scoredkmoney = 0;
					}
					
					$leveldkmoney = $order['leveldk_money'] ?? 0;
					if($bset['leveldk_kouchu'] == 0){ //扣除积分抵扣
						$leveldkmoney = 0;
					}

					$totalmoney = $order['product_price'] + $order['freight_price'] - $order['coupon_money'] - $order['leader_money'] - $order['discount_money_admin'] - $scoredkmoney - $leveldkmoney;
                    if($totalmoney > 0){
						if(getcustom('business_deduct_cost')){
                        	if($binfo && $binfo['deduct_cost'] == 1 && $order['cost_price']>0){
                        		if($order['cost_price']<=$order['sell_price']){
									$all_cost_price = $order['cost_price'];
								}else{
									$all_cost_price = $order['sell_price'];
								}
	                        	//扣除成本
                                $platformMoney = ($totalmoney-$all_cost_price)*$binfo['feepercent']/100;
                            }else{
                                $platformMoney = $totalmoney * $binfo['feepercent'] * 0.01;
                            }
                        }else {
                            $platformMoney = $totalmoney * $binfo['feepercent'] * 0.01;
                        }
                        if(getcustom('business_fee_type')){
                            if($bset['business_fee_type'] == 1){
                                $platformMoney = ($order['totalprice']-$order['freight_price']) * $binfo['feepercent'] * 0.01;
                            }elseif($bset['business_fee_type'] == 2){
                                $platformMoney = $order['cost_price'] * $binfo['feepercent'] * 0.01;
                            }
                        } 
                        $totalmoney = $totalmoney - $platformMoney;
					}
				}
                
                if($order['paytypeid']==4){
                    $totalmoney = $totalmoney - $order['totalprice'];
                }
                $isbusinesspay = Db::name('payorder')->where('aid',$aid)->where('ordernum',$order['ordernum'])->value('isbusinesspay');
                if(!$isbusinesspay){
                    if($totalmoney < 0){
                        $bmoney = Db::name('business')->where('aid',$aid)->where('id',$order['bid'])->value('money');
                        if($bmoney + $totalmoney < 0){
                            return ['status'=>0,'msg'=>'操作失败,商家余额不足'];
                        }
                    }
                    \app\common\Business::addmoney($aid,$order['bid'],$totalmoney,'货款，周期购订单号：'.$order['ordernum'],true,$type,$order['ordernum'],['platformMoney'=>$platformMoney,'business_lirun'=>$business_lirun]);
                }else{
                	//商家推荐分成
					if($totalmoney > 0){
						if(getcustom('business_agent')){
							\app\common\Business::addparentcommission2($aid,$order['bid'],$totalmoney,$platformMoney,$business_lirun);
						}else{
							\app\common\Business::addparentcommission($aid,$order['bid'],$totalmoney);
						}
					}
                }
                //店铺加销量
                Db::name('business')->where('aid',$aid)->where('id',$order['bid'])->inc('sales',$order['num'])->update();

				if(getcustom('business_canuseplatcoupon') && $order['coupon_money'] > 0 && $order['coupon_rid'] > 0){
					$couponrecord = Db::name('coupon_record')->where('id',$order['coupon_rid'])->find();
					if($couponrecord && $couponrecord['bid'] == 0){
						$businessuserecord = [];
						$businessuserecord['aid'] = $order['aid'];
						$businessuserecord['bid'] = $order['bid'];
						$businessuserecord['mid'] = $order['mid'];
						$businessuserecord['ordertype'] = $type;
						$businessuserecord['orderid'] = $order['id'];
						$businessuserecord['couponrid'] = $order['coupon_rid'];
						$businessuserecord['couponid'] = $couponrecord['couponid'];
						$businessuserecord['couponname'] = $couponrecord['couponname'];
						$businessuserecord['couponmoney'] = $couponrecord['money'];
						$businessuserecord['decmoney'] = $order['coupon_money'];
						$businessuserecord['status'] = 1;
						$businessuserecord['createtime'] = time();
						Db::name('coupon_businessuserecord')->insert($businessuserecord);
						Db::name('business')->where('id',$order['bid'])->inc('couponmoney',$order['coupon_money'])->update();
					}
				}
            }
        }elseif($type=='yuyue'){
			if($order['bid']!=0){//入驻商家的货款

				$binfo = Db::name('business')->where('aid',$aid)->where('id',$order['bid'])->find();
				if(getcustom('hmy_yuyue')){
					$totalmoney = $order['totalprice']+$order['balance_price']-$order['paidan_money'];
				}else{
					$totalmoney = $order['product_price'];
				}
				if($totalmoney > 0){
                    $platformMoney = $totalmoney * $binfo['feepercent'] * 0.01;
                    $totalmoney = $totalmoney - $platformMoney;
				}
				$isbusinesspay = Db::name('payorder')->where('aid',$aid)->where('ordernum',$order['ordernum'])->value('isbusinesspay');
				if(!$isbusinesspay){
					if($totalmoney < 0){
						$bmoney = Db::name('business')->where('aid',$aid)->where('id',$order['bid'])->value('money');
						if($bmoney + $totalmoney < 0){
							return ['status'=>0,'msg'=>'操作失败,商家余额不足'];
						}
					}
					$worker_order = Db::name('yuyue_worker_order')->where('id',$order['worker_orderid'])->find();
					if(getcustom('hmy_yuyue')){
						//获取师傅信息
						$rs = \app\custom\Yuyue::getMaster($worker_order['worker_id']);
						$worker = [];
						$worker['realname'] =$rs['data']['name'];
						$worker['tel'] = $rs['data']['phone']?$rs['data']['phone']:'';
					}else{
						$worker = Db::name('yuyue_worker')->where('id',$worker_order['worker_id'])->find();
					}
					\app\common\Business::addmoney($aid,$order['bid'],$totalmoney,'服务订单/('.$worker['realname'].')'.$worker['tel'].' /:'.$order['ordernum'],true,$type,$order['ordernum'],['platformMoney'=>$platformMoney,'business_lirun'=>$business_lirun]);
				}else{
                	//商家推荐分成
					if($totalmoney > 0){
						if(getcustom('business_agent')){
							\app\common\Business::addparentcommission2($aid,$order['bid'],$totalmoney,$platformMoney);
						}else{
							\app\common\Business::addparentcommission($aid,$order['bid'],$totalmoney);
						}
					}
                }
				//店铺加销量
				Db::name('business')->where('aid',$aid)->where('id',$order['bid'])->inc('sales',$order['num'])->update();

				if(getcustom('business_canuseplatcoupon') && $order['coupon_money'] > 0 && $order['coupon_rid'] > 0){
					$couponrecord = Db::name('coupon_record')->where('id',$order['coupon_rid'])->find();
					if($couponrecord && $couponrecord['bid'] == 0){
						$businessuserecord = [];
						$businessuserecord['aid'] = $order['aid'];
						$businessuserecord['bid'] = $order['bid'];
						$businessuserecord['mid'] = $order['mid'];
						$businessuserecord['ordertype'] = $type;
						$businessuserecord['orderid'] = $order['id'];
						$businessuserecord['couponrid'] = $order['coupon_rid'];
						$businessuserecord['couponid'] = $couponrecord['couponid'];
						$businessuserecord['couponname'] = $couponrecord['couponname'];
						$businessuserecord['couponmoney'] = $couponrecord['money'];
						$businessuserecord['decmoney'] = $order['coupon_money'];
						$businessuserecord['status'] = 1;
						$businessuserecord['createtime'] = time();
						Db::name('coupon_businessuserecord')->insert($businessuserecord);
						Db::name('business')->where('id',$order['bid'])->inc('couponmoney',$order['coupon_money'])->update();
					}
				}
			}
			//赠积分
            if($order['givescore'] > 0){
				if($order['bid'] > 0){
					\app\common\Business::addmemberscore($aid,$order['bid'],$order['mid'],$order['givescore'],'购买商品赠送'.t('积分'));
				}else{
					\app\common\Member::addscore($aid,$order['mid'],$order['givescore'],'购买商品赠送'.t('积分'));
				}
            }
		}elseif($type=='lucky_collage'){
			if($order['bid']!=0){//入驻商家的货款

				$binfo = Db::name('business')->where('aid',$aid)->where('id',$order['bid'])->find();
				$totalcommission = 0;
				//if($order['iscommission']){
				if($order['parent1'] && $order['parent1commission'] > 0){
					$totalcommission += $order['parent1commission'];
				}
				if($order['parent2'] && $order['parent2commission'] > 0){
					$totalcommission += $order['parent2commission'];
				}
				if($order['parent3'] && $order['parent3commission'] > 0){
					$totalcommission += $order['parent3commission'];
				}
				//}
				$binfo = Db::name('business')->where('aid',$aid)->where('id',$order['bid'])->find();
				$bset = Db::name('business_sysset')->where('aid',$aid)->find();
				if($bset['commission_kouchu'] == 0){ //不扣除佣金
					$totalcommission = 0;
				}
				$scoredkmoney = $order['scoredk_money'] ?? 0;
				if($bset['scoredk_kouchu'] == 0){ //扣除积分抵扣
					$scoredkmoney = 0;
				}
				
				$leveldkmoney = $order['leveldk_money'] ?? 0;
				if($bset['leveldk_kouchu'] == 0){ //扣除积分抵扣
					$leveldkmoney = 0;
				}
				
				$totalmoney = $order['product_price'] + $order['freight_price'] - $order['coupon_money'] - $order['leader_money'] - $totalcommission - $scoredkmoney - $leveldkmoney;
				if($totalmoney > 0){
                    $platformMoney = $totalmoney * $binfo['feepercent'] * 0.01;
                    $totalmoney = $totalmoney - $platformMoney;
				}
				
				if($order['paytypeid']==4){
					$totalmoney = $totalmoney - $order['totalprice'];
				}
				$isbusinesspay = Db::name('payorder')->where('aid',$aid)->where('ordernum',$order['ordernum'])->value('isbusinesspay');
				if(!$isbusinesspay){
					if($totalmoney < 0){
						$bmoney = Db::name('business')->where('aid',$aid)->where('id',$order['bid'])->value('money');
						if($bmoney + $totalmoney < 0){
							return ['status'=>0,'msg'=>'操作失败,商家余额不足'];
						}
					}
					\app\common\Business::addmoney($aid,$order['bid'],$totalmoney,'货款，幸运拼团订单号：'.$order['ordernum'],true,$type,$order['ordernum'],['platformMoney'=>$platformMoney]);
				}else{
                	//商家推荐分成
					if($totalmoney > 0){
						if(getcustom('business_agent')){
							\app\common\Business::addparentcommission2($aid,$order['bid'],$totalmoney,$platformMoney);
						}else{
							\app\common\Business::addparentcommission($aid,$order['bid'],$totalmoney);
						}
					}
                }
				//店铺加销量
				Db::name('business')->where('aid',$aid)->where('id',$order['bid'])->inc('sales',$order['num'])->update();
				
				if(getcustom('business_canuseplatcoupon') && $order['coupon_money'] > 0 && $order['coupon_rid'] > 0){
					$couponrecord = Db::name('coupon_record')->where('id',$order['coupon_rid'])->find();
					if($couponrecord && $couponrecord['bid'] == 0){
						$businessuserecord = [];
						$businessuserecord['aid'] = $order['aid'];
						$businessuserecord['bid'] = $order['bid'];
						$businessuserecord['mid'] = $order['mid'];
						$businessuserecord['ordertype'] = $type;
						$businessuserecord['orderid'] = $order['id'];
						$businessuserecord['couponrid'] = $order['coupon_rid'];
						$businessuserecord['couponid'] = $couponrecord['couponid'];
						$businessuserecord['couponname'] = $couponrecord['couponname'];
						$businessuserecord['couponmoney'] = $couponrecord['money'];
						$businessuserecord['decmoney'] = $order['coupon_money'];
						$businessuserecord['status'] = 1;
						$businessuserecord['createtime'] = time();
						Db::name('coupon_businessuserecord')->insert($businessuserecord);
						Db::name('business')->where('id',$order['bid'])->inc('couponmoney',$order['coupon_money'])->update();
					}
				}
			}
		}elseif($type=='kanjia'){
			if($order['bid']!=0){//入驻商家的货款

				$binfo = Db::name('business')->where('aid',$aid)->where('id',$order['bid'])->find();
				if(!is_null($order['business_total_money'])) {
					$totalmoney = $order['business_total_money'];
                    $platformMoney = $order['totalprice']-$totalmoney - $order['refund_money'];
				} else {
					$bset = Db::name('business_sysset')->where('aid',$aid)->find();
					$scoredkmoney = $order['scoredk_money'] ?? 0;
					if($bset['scoredk_kouchu'] == 0){ //扣除积分抵扣
						$scoredkmoney = 0;
					}
					$totalmoney = $order['product_price'] + $order['freight_price'] - $scoredkmoney;
					if($totalmoney > 0){
                        $platformMoney = $totalmoney * $binfo['feepercent'] * 0.01;
                        $totalmoney = $totalmoney - $platformMoney;
					}
				}

				if($order['paytypeid']==4){
					$totalmoney = $totalmoney - $order['totalprice'];
				}
				$isbusinesspay = Db::name('payorder')->where('aid',$aid)->where('ordernum',$order['ordernum'])->value('isbusinesspay');
				if(!$isbusinesspay){
					if($totalmoney < 0){
						$bmoney = Db::name('business')->where('aid',$aid)->where('id',$order['bid'])->value('money');
						if($bmoney + $totalmoney < 0){
							return ['status'=>0,'msg'=>'操作失败,商家余额不足'];
						}
					}
					\app\common\Business::addmoney($aid,$order['bid'],$totalmoney,'货款，砍价订单号：'.$order['ordernum'],true,$type,$order['ordernum'],['platformMoney'=>$platformMoney]);
				}else{
                	//商家推荐分成
					if($totalmoney > 0){
						if(getcustom('business_agent')){
							\app\common\Business::addparentcommission2($aid,$order['bid'],$totalmoney,$platformMoney);
						}else{
							\app\common\Business::addparentcommission($aid,$order['bid'],$totalmoney);
						}
					}
                }
				//店铺加销量
				Db::name('business')->where('aid',$aid)->where('id',$order['bid'])->inc('sales',$order['num'])->update();
				
				if(getcustom('business_canuseplatcoupon') && $order['coupon_money'] > 0 && $order['coupon_rid'] > 0){
					$couponrecord = Db::name('coupon_record')->where('id',$order['coupon_rid'])->find();
					if($couponrecord && $couponrecord['bid'] == 0){
						$businessuserecord = [];
						$businessuserecord['aid'] = $order['aid'];
						$businessuserecord['bid'] = $order['bid'];
						$businessuserecord['mid'] = $order['mid'];
						$businessuserecord['ordertype'] = $type;
						$businessuserecord['orderid'] = $order['id'];
						$businessuserecord['couponrid'] = $order['coupon_rid'];
						$businessuserecord['couponid'] = $couponrecord['couponid'];
						$businessuserecord['couponname'] = $couponrecord['couponname'];
						$businessuserecord['couponmoney'] = $couponrecord['money'];
						$businessuserecord['decmoney'] = $order['coupon_money'];
						$businessuserecord['status'] = 1;
						$businessuserecord['createtime'] = time();
						Db::name('coupon_businessuserecord')->insert($businessuserecord);
						Db::name('business')->where('id',$order['bid'])->inc('couponmoney',$order['coupon_money'])->update();
					}
				}
			}
		}elseif($type=='seckill'){
			if($order['bid']!=0){//入驻商家的货款
				
				$totalcommission = 0;
				if($order['parent1'] && $order['parent1commission'] > 0){
					$totalcommission += $order['parent1commission'];
				}
				if($order['parent2'] && $order['parent2commission'] > 0){
					$totalcommission += $order['parent2commission'];
				}
				if($order['parent3'] && $order['parent3commission'] > 0){
					$totalcommission += $order['parent3commission'];
				}
				$binfo = Db::name('business')->where('aid',$aid)->where('id',$order['bid'])->find();
				$bset = Db::name('business_sysset')->where('aid',$aid)->find();
				if($bset['commission_kouchu'] == 0){ //不扣除佣金
					$totalcommission = 0;
				}
                if(getcustom('business_agent')){
                    $lirun_cost_price = 0;
                    if($order['cost_price']>0){
                        $lirun_cost_price = $order['cost_price'];                           
                    }                    
                    $business_lirun = $order['totalprice'] - $order['refund_money'] - $lirun_cost_price;
                }
				
				if(!is_null($order['business_total_money'])) {
					$leveldkmoney = $order['leveldk_money'] ?? 0;
					if($bset['leveldk_kouchu'] == 0){ //扣除会员抵扣
						$leveldkmoney = 0;
					}
					$totalmoney = $order['business_total_money'] - $totalcommission - $leveldkmoney;
                    $platformMoney = $order['totalprice']-$totalmoney - $order['refund_money'];
				} else {
					$scoredkmoney = $order['scoredk_money'] ?? 0;
					if($bset['scoredk_kouchu'] == 0){ //扣除积分抵扣
						$scoredkmoney = 0;
					}
					$leveldkmoney = $order['leveldk_money'] ?? 0;
					if($bset['leveldk_kouchu'] == 0){ //扣除积分抵扣
						$leveldkmoney = 0;
					}
					$totalmoney = $order['product_price'] + $order['freight_price'] - $order['coupon_money'] - $order['manjia_money'] - $totalcommission - $scoredkmoney - $leveldkmoney;
					if($totalmoney > 0){
						if(getcustom('business_deduct_cost')){
                        	if($binfo && $binfo['deduct_cost'] == 1 && $order['cost_price']>0){
                        		if($order['cost_price']<=$order['sell_price']){
									$all_cost_price = $order['cost_price'];
								}else{
									$all_cost_price = $order['sell_price'];
								}
	                        	//扣除成本
                                $platformMoney = ($totalmoney-$all_cost_price)*$binfo['feepercent']/100;
                            }else{
                                $platformMoney = $totalmoney * $binfo['feepercent'] * 0.01;
                            }
                            
		                }else{
                            $platformMoney = $totalmoney * $binfo['feepercent'] * 0.01;
                            
		                }
                        if(getcustom('business_fee_type')){
                            if($bset['business_fee_type'] == 1){
                                $platformMoney = ($order['totalprice']-$order['freight_price']) * $binfo['feepercent'] * 0.01;
                            }elseif($bset['business_fee_type'] == 2){
                                $platformMoney = $order['cost_price'] * $binfo['feepercent'] * 0.01;
                            }
                        } 
                        $totalmoney = $totalmoney - $platformMoney;
					}
				}

				if($order['paytypeid']==4){
					$totalmoney = $totalmoney - $order['totalprice'];
				}
				$isbusinesspay = Db::name('payorder')->where('aid',$aid)->where('ordernum',$order['ordernum'])->value('isbusinesspay');
				if(!$isbusinesspay){
					if($totalmoney < 0){
						$bmoney = Db::name('business')->where('aid',$aid)->where('id',$order['bid'])->value('money');
						if($bmoney + $totalmoney < 0){
							return ['status'=>0,'msg'=>'操作失败,商家余额不足'];
						}
					}
					\app\common\Business::addmoney($aid,$order['bid'],$totalmoney,'货款，秒杀订单号：'.$order['ordernum'],true,$type,$order['ordernum'],['platformMoney'=>$platformMoney,'business_lirun'=>$business_lirun]);
				}else{
                	//商家推荐分成
					if($totalmoney > 0){
						if(getcustom('business_agent')){
							\app\common\Business::addparentcommission2($aid,$order['bid'],$totalmoney,$platformMoney,$business_lirun);
						}else{
							\app\common\Business::addparentcommission($aid,$order['bid'],$totalmoney);
						}
					}
                }
                //店铺加销量
                Db::name('business')->where('aid',$aid)->where('id',$order['bid'])->inc('sales',$order['num'])->update();

				if(getcustom('business_canuseplatcoupon') && $order['coupon_money'] > 0 && $order['coupon_rid'] > 0){
					$couponrecord = Db::name('coupon_record')->where('id',$order['coupon_rid'])->find();
					if($couponrecord && $couponrecord['bid'] == 0){
						$businessuserecord = [];
						$businessuserecord['aid'] = $order['aid'];
						$businessuserecord['bid'] = $order['bid'];
						$businessuserecord['mid'] = $order['mid'];
						$businessuserecord['ordertype'] = $type;
						$businessuserecord['orderid'] = $order['id'];
						$businessuserecord['couponrid'] = $order['coupon_rid'];
						$businessuserecord['couponid'] = $couponrecord['couponid'];
						$businessuserecord['couponname'] = $couponrecord['couponname'];
						$businessuserecord['couponmoney'] = $couponrecord['money'];
						$businessuserecord['decmoney'] = $order['coupon_money'];
						$businessuserecord['status'] = 1;
						$businessuserecord['createtime'] = time();
						Db::name('coupon_businessuserecord')->insert($businessuserecord);
						Db::name('business')->where('id',$order['bid'])->inc('couponmoney',$order['coupon_money'])->update();
					}
				}
            }
            //赠积分
            if($order['givescore'] > 0){
                \app\common\Member::addscore($aid,$order['mid'],$order['givescore'],'购买产品赠送'.t('积分'));
            }
		}elseif($type=='coupon'){
			if($order['bid']!=0){//入驻商家的货款
				$binfo = Db::name('business')->where('aid',$aid)->where('id',$order['bid'])->find();
				$totalmoney = $order['price'];
				if($totalmoney > 0){
                    $platformMoney = $totalmoney * $binfo['feepercent'] * 0.01;
                    $totalmoney = $totalmoney - $platformMoney;
				}
				$isbusinesspay = Db::name('payorder')->where('aid',$aid)->where('ordernum',$order['ordernum'])->value('isbusinesspay');
				if(!$isbusinesspay){
					\app\common\Business::addmoney($aid,$order['bid'],$totalmoney,'销售'.t('优惠券').' 订单号：'.$order['ordernum'],true,$type,$order['ordernum'],['platformMoney'=>$platformMoney]);
				}else{
                	//商家推荐分成
					if($totalmoney > 0){
						if(getcustom('business_agent')){
							\app\common\Business::addparentcommission2($aid,$order['bid'],$totalmoney,$platformMoney);
						}else{
							\app\common\Business::addparentcommission($aid,$order['bid'],$totalmoney);
						}
					}
                }
			}
		}elseif($type=='maidan'){
			$totalcommission = 0;
			$maidanfenxiao = Db::name('admin_set')->where('aid',$aid)->value('maidanfenxiao');
            if(getcustom('maidan_qrcode')) {
                $maidanfenxiao = 0;
            }
			if($maidanfenxiao == 1){ //参与分销
				$member = Db::name('member')->where('aid',$aid)->where('id',$order['mid'])->find();
				$agleveldata = Db::name('member_level')->where('aid',$aid)->where('id',$member['levelid'])->find();
				if($agleveldata['can_agent'] > 0 && $agleveldata['commission1own']==1){
					$member['pid'] = $member['id'];
				}
				$isCommissionScore = 0;
				if(getcustom('maidan_commission_score')){
                    $isCommissionScore = 1;
                }
				if(getcustom('maidan_fenhong_new')){
                    //买单分销结算方式
                    $sysset = Db::name('admin_set')->where('aid',$aid)->field('maidanfenxiao_type,maidan_cost')->find();
                    $maidanfenhong_type = $sysset['maidanfenxiao_type'];
                    if($maidanfenhong_type == 1){
                        //按利润结算时直接把销售额改成利润
                        if($order['bid']>0){
                            $maidan_cost = Db::name('business')->where('id',$order['bid'])->value('maidan_cost');
                        }else{
                            $maidan_cost = $sysset['maidan_cost'];
                        }
                        $cost_price = bcmul($order['paymoney'],$maidan_cost/100,2);
                        $order['paymoney'] = $order['paymoney'] - $cost_price;
                    }
                }
				$ogdata = [];
                //是否积分提成
                $ogdata['isparent1score'] = 0;
                $ogdata['isparent2score'] = 0;
                $ogdata['isparent3score'] = 0;
				if($member['pid']){
					$parent1 = Db::name('member')->where('aid',$aid)->where('id',$member['pid'])->find();
					if($parent1){
						$agleveldata1 = Db::name('member_level')->where('aid',$aid)->where('id',$parent1['levelid'])->find();
						if($agleveldata1['can_agent']!=0){
							$ogdata['parent1'] = $parent1['id'];
							if($isCommissionScore && $agleveldata1['maidan_commission_score1']>0){
                                $ogdata['isparent1score'] = 1;
                                $ogdata['parent1score'] = round($agleveldata1['maidan_commission_score1'] * $order['paymoney'] * 0.01);
                            }
						}
					}
				}
				if($parent1['pid']){
					$parent2 = Db::name('member')->where('aid',$aid)->where('id',$parent1['pid'])->find();
					if($parent2){
						$agleveldata2 = Db::name('member_level')->where('aid',$aid)->where('id',$parent2['levelid'])->find();
						if($agleveldata2['can_agent']>1){
							$ogdata['parent2'] = $parent2['id'];
                            if($isCommissionScore && $agleveldata2['maidan_commission_score2']>0){
                                $ogdata['isparent2score'] = 1;
                                $ogdata['parent2score'] = round($agleveldata2['maidan_commission_score2'] * $order['paymoney'] * 0.01);
                            }
						}
					}
				}
				if($parent2['pid']){
					$parent3 = Db::name('member')->where('aid',$aid)->where('id',$parent2['pid'])->find();
					if($parent3){
						$agleveldata3 = Db::name('member_level')->where('aid',$aid)->where('id',$parent3['levelid'])->find();
						if($agleveldata3['can_agent']>2){
							$ogdata['parent3'] = $parent3['id'];
                            if($isCommissionScore &&  $agleveldata3['maidan_commission_score3']>0){
                                $ogdata['isparent3score'] = 1;
                                $ogdata['parent3score'] = round($agleveldata3['maidan_commission_score3'] * $order['paymoney'] * 0.01);
                            }
						}
					}
				}
				$ogdata['parent1commission'] = $agleveldata1['commission1'] * $order['paymoney'] * 0.01;
				$ogdata['parent2commission'] = $agleveldata2['commission2'] * $order['paymoney'] * 0.01;
				$ogdata['parent3commission'] = $agleveldata3['commission3'] * $order['paymoney'] * 0.01;
				if($ogdata['parent1'] && $ogdata['isparent1score']==1){
                    $ogdata['parent1score']>0 && \app\common\Member::addscore($aid,$ogdata['parent1'],$ogdata['parent1score'],'下级买单'.t('积分').'奖励');
                }elseif($ogdata['parent1'] && $ogdata['isparent1score']==0 && $ogdata['parent1commission'] > 0){
					$totalcommission+=$ogdata['parent1commission'];
					\app\common\Member::addcommission($aid,$ogdata['parent1'],$mid,$ogdata['parent1commission'],'下级买单收款奖励');
					Db::name('member_commission_record')->insert(['aid'=>$aid,'mid'=>$ogdata['parent1'],'frommid'=>$order['mid'],'orderid'=>$order['id'],'type'=>'maidan','commission'=>$ogdata['parent1commission'],'remark'=>'下级买单收款奖励','createtime'=>time(),'status'=>1,'endtime'=>time()]);
				}
                if($ogdata['parent2'] && $ogdata['isparent2score']==1){
                    $ogdata['parent2score']>0 && \app\common\Member::addscore($aid,$ogdata['parent2'],$ogdata['parent2score'],'下二级买单'.t('积分').'奖励');
                }elseif($ogdata['parent2'] && $ogdata['isparent2score']==0 && $ogdata['parent2commission'] > 0){
					$totalcommission+=$ogdata['parent2commission'];
					\app\common\Member::addcommission($aid,$ogdata['parent2'],$mid,$ogdata['parent2commission'],'下二级买单收款奖励');
					Db::name('member_commission_record')->insert(['aid'=>$aid,'mid'=>$ogdata['parent2'],'frommid'=>$order['mid'],'orderid'=>$order['id'],'type'=>'maidan','commission'=>$ogdata['parent2commission'],'remark'=>'下二级买单收款奖励','createtime'=>time(),'status'=>1,'endtime'=>time()]);
				}
                if($ogdata['parent3'] && $ogdata['isparent3score']==1){
                    $ogdata['parent3score']>0 && \app\common\Member::addscore($aid,$ogdata['parent3'],$ogdata['parent3score'],'下三级买单'.t('积分').'奖励');
                }elseif($ogdata['parent3'] && $ogdata['isparent3score']==0 && $ogdata['parent3commission'] > 0){
					$totalcommission+=$ogdata['parent3commission'];
					\app\common\Member::addcommission($aid,$ogdata['parent3'],$mid,$ogdata['parent3commission'],'下三级买单收款奖励');
					Db::name('member_commission_record')->insert(['aid'=>$aid,'mid'=>$ogdata['parent3'],'frommid'=>$order['mid'],'orderid'=>$order['id'],'type'=>'maidan','commission'=>$ogdata['parent3commission'],'remark'=>'下三级买单收款奖励','createtime'=>time(),'status'=>1,'endtime'=>time()]);
				}
				if($ogdata['parent1']){
					\app\common\Member::uplv($aid,$ogdata['parent1']);
				}
				$bset = Db::name('business_sysset')->where('aid',$aid)->find();
                if($bset['commission_kouchu'] == 0){ //不扣除佣金
                    $totalcommission = 0;
                }
			}

			if($order['bid']!=0){//入驻商家的货款

				$binfo = Db::name('business')->where('aid',$aid)->where('id',$order['bid'])->find();
				$totalmoney = $order['money'] - $order['couponmoney'] - $totalcommission;
				if($totalmoney > 0){
                    $platformMoney = $totalmoney * $binfo['feepercent'] * 0.01;
                    $totalmoney = $totalmoney - $platformMoney;
				}
				$isbusinesspay = Db::name('payorder')->where('aid',$aid)->where('ordernum',$order['ordernum'])->value('isbusinesspay');
				if(!$isbusinesspay){
					\app\common\Business::addmoney($aid,$order['bid'],$totalmoney,'买单 订单号：'.$order['ordernum'],true,$type,$order['ordernum'],['platformMoney'=>$platformMoney]);
				}else{
                	//商家推荐分成
					if($totalmoney > 0){
						if(getcustom('business_agent')){
							\app\common\Business::addparentcommission2($aid,$order['bid'],$totalmoney,$platformMoney);
						}else{
							\app\common\Business::addparentcommission($aid,$order['bid'],$totalmoney);
						}
					}
                }
				if(getcustom('business_canuseplatcoupon') && $order['couponmoney'] > 0 && $order['couponrid'] > 0){
					$couponrecord = Db::name('coupon_record')->where('id',$order['couponrid'])->find();
					if($couponrecord && $couponrecord['bid'] == 0){
						$businessuserecord = [];
						$businessuserecord['aid'] = $order['aid'];
						$businessuserecord['bid'] = $order['bid'];
						$businessuserecord['mid'] = $order['mid'];
						$businessuserecord['ordertype'] = $type;
						$businessuserecord['orderid'] = $order['id'];
						$businessuserecord['couponrid'] = $order['couponrid'];
						$businessuserecord['couponid'] = $couponrecord['couponid'];
						$businessuserecord['couponname'] = $couponrecord['couponname'];
						$businessuserecord['couponmoney'] = $couponrecord['money'];
						$businessuserecord['decmoney'] = $order['couponmoney'];
						$businessuserecord['status'] = 1;
						$businessuserecord['createtime'] = time();
						Db::name('coupon_businessuserecord')->insert($businessuserecord);
						Db::name('business')->where('id',$order['bid'])->inc('couponmoney',$order['couponmoney'])->update();
					}
				}
			}
			
            if(getcustom('yx_queue_free')){
                \app\custom\QueueFree::join($order,$type);
            }
				
			if(getcustom('mendian_maidan_ticheng')){
				if($order['mdid']>0){
					$mendian = 	Db::name('mendian')->field('id,maidangivepercent,maidangivemoney')->where('id',$order['mdid'])->find();
					if($mendian['maidangivepercent']>0 || $mendian['maidangivemoney']>0){
						$givemoney += $order['paymoney'] * 0.01 * $mendian['maidangivepercent'] + $mendian['maidangivemoney'];
						if($givemoney > 0){
							\app\common\Mendian::addmoney($order['aid'],$mendian['id'],$givemoney,'买单提成'.$order['ordernum']);
						}
					}
				}
			
			}


		}elseif($type=='designerpage'){
			if($order['bid']!=0){//入驻商家的货款
				$binfo = Db::name('business')->where('aid',$aid)->where('id',$order['bid'])->find();
				$totalmoney = $order['price'];
				if($totalmoney > 0){
                    $platformMoney = $totalmoney * $binfo['feepercent'] * 0.01;
                    $totalmoney = $totalmoney - $platformMoney;
				}
				$isbusinesspay = Db::name('payorder')->where('aid',$aid)->where('ordernum',$order['ordernum'])->value('isbusinesspay');
				if(!$isbusinesspay){
					\app\common\Business::addmoney($aid,$order['bid'],$totalmoney,'付费查看页面 订单号：'.$order['ordernum'],true,$type,$order['ordernum'],['platformMoney'=>$platformMoney]);
				}else{
                	//商家推荐分成
					if($totalmoney > 0){
						if(getcustom('business_agent')){
							\app\common\Business::addparentcommission2($aid,$order['bid'],$totalmoney,$platformMoney);
						}else{
							\app\common\Business::addparentcommission($aid,$order['bid'],$totalmoney);
						}
					}
                }
			}
		}elseif($type == 'scoreshop') {
            //门店分成
            if($order['mdid'] && $commission_mid) {
                $orderGoods = Db::name($type.'_order_goods')->where('orderid',$order['id'])->select()->toArray();
                foreach ($orderGoods as $og) {
                    if($og['mendian_iscommission'] == 0 && $og['mendian_commission'] > 0 && $og['mendian_score'] > 0){
                        if($og['mendian_commission'] > 0) {
                            \app\common\Member::addcommission($aid, $commission_mid, $order['mid'], $og['mendian_commission'], '门店核销：'.$order['ordernum']);
                        }
                        if($og['mendian_score'] > 0) {
                            \app\common\Member::addscore($aid, $commission_mid, $og['mendian_score'],'门店核销：'.$order['ordernum']);
                        }
                        Db::name($type.'_order_goods')->where('id',$og['id'])->update(['mendian_iscommission' => 1]);
                    }
                }
            }
			if($order['bid']!=0){//入驻商家的货款

				$binfo = Db::name('business')->where('aid',$aid)->where('id',$order['bid'])->find();
				$bset = Db::name('business_sysset')->where('aid',$aid)->find();
                if(getcustom('business_agent')){
                    $lirun_cost_price = 0;
                    if($order['cost_price']>0){
                        $lirun_cost_price = $order['cost_price'];                           
                    }                    
                    $business_lirun = $order['totalprice'] - $order['refund_money'] - $lirun_cost_price;
                }

				if(!is_null($order['business_total_money'])) {
					$totalmoney = $order['business_total_money'];
                    $platformMoney = $order['totalprice']-$totalmoney - $order['refund_money'];
				} else {
					$totalmoney = $order['totalmoney'] + $order['freight_price'];
					if($totalmoney > 0){
						if(getcustom('business_deduct_cost')){
							//获取商品成
							$orderGoods = Db::name($type.'_order_goods')->where('orderid',$order['id'])->select()->toArray();
			                $all_cost_price = 0;
			                if($orderGoods){
			                	foreach ($orderGoods as $og) {
				                    if(!empty($og['cost_price']) && $og['cost_price']>0){
										if($og['cost_price']<=$og['sell_price']){
											$all_cost_price += $og['cost_price'];
										}else{
											$all_cost_price += $og['sell_price'];
										}
									}
				                }
			                }

                        	if($binfo && $binfo['deduct_cost'] == 1){
	                        	//扣除成本
                                $platformMoney = ($totalmoney-$all_cost_price)*$binfo['feepercent']/100;
                            }else{
                                $platformMoney = $totalmoney * $binfo['feepercent'] * 0.01;
                            }
                            
                        }else{
                            $platformMoney = $totalmoney * $binfo['feepercent'] * 0.01;
                            
                        }
                        if(getcustom('business_fee_type')){
                            if($bset['business_fee_type'] == 1){
                                $platformMoney = ($order['totalprice']-$order['freight_price']) * $binfo['feepercent'] * 0.01;
                            }elseif($bset['business_fee_type'] == 2){
                                //获取商品成
                                $orderGoods = Db::name($type.'_order_goods')->where('orderid',$order['id'])->select()->toArray();
                                $total_cost_price = 0;
                                if($orderGoods){
                                    foreach ($orderGoods as $og) {
                                        if(!empty($og['cost_price']) && $og['cost_price']>0){  
                                                $total_cost_price += $og['cost_price'];
                                        }
                                    }
                                }
                                $platformMoney = $total_cost_price * $binfo['feepercent'] * 0.01;
                            }
                        } 
                        $totalmoney = $totalmoney - $platformMoney;
						
					}
				}
				
				if($order['paytypeid']==4){
					$totalmoney = $totalmoney - $order['totalprice'];
				}
				$isbusinesspay = Db::name('payorder')->where('aid',$aid)->where('ordernum',$order['ordernum'])->value('isbusinesspay');
				if(!$isbusinesspay){
					if($totalmoney < 0){
						$bmoney = Db::name('business')->where('aid',$aid)->where('id',$order['bid'])->value('money');
						if($bmoney + $totalmoney < 0){
							return ['status'=>0,'msg'=>'操作失败,商家余额不足'];
						}
					}
					\app\common\Business::addmoney($aid,$order['bid'],$totalmoney,'货款，砍价订单号：'.$order['ordernum'],true,$type,$order['ordernum'],['platformMoney'=>$platformMoney,'business_lirun'=>$business_lirun]);
				}else{
                	//商家推荐分成
					if($totalmoney > 0){
						if(getcustom('business_agent')){
							\app\common\Business::addparentcommission2($aid,$order['bid'],$totalmoney,$platformMoney,$business_lirun);
						}else{
							\app\common\Business::addparentcommission($aid,$order['bid'],$totalmoney);
						}
					}
                }
				$bset = Db::name('business_sysset')->where('aid',$aid)->find();
				if($bset['business_selfscore'] == 1){
					$totalscore = Db::name('scoreshop_order_goods')->where('orderid',$order['id'])->sum('totalscore');
					if($totalscore > 0 && $order['totalscore'] == 0){
						\app\common\Business::addscore($aid,$order['bid'],$totalscore,'用户兑换商品，订单号：'.$order['ordernum'],1);
					}
				}
				//店铺加销量
				$totalnum = Db::name('scoreshop_order_goods')->where('orderid',$order['id'])->sum('num');
				Db::name('business')->where('aid',$aid)->where('id',$order['bid'])->inc('sales',$totalnum)->update();
			}
        }elseif($type=='tuangou'){
            if($order['bid']!=0){//入驻商家的货款

				$binfo = Db::name('business')->where('aid',$aid)->where('id',$order['bid'])->find();

                if(getcustom('business_agent')){
                    $lirun_cost_price = 0;
                    if($order['cost_price']>0){
                        $lirun_cost_price = $order['cost_price'];                           
                    }                    
                    $business_lirun = $order['totalprice'] - $order['refund_money'] - $lirun_cost_price;
                }

				$totalmoney = $order['product_price'] + $order['freight_price'] * (100-$binfo['feepercent_freight']) * 0.01 - $order['coupon_money'] - $order['manjia_money'];
				if($order['paytypeid']==4){
					$totalmoney = $totalmoney - $order['totalprice'];
				}
				$bset = Db::name('business_sysset')->where('aid',$aid)->find();
				$scoredkmoney = $order['scoredk_money'] ?? 0;
				if($bset['scoredk_kouchu'] == 0){ //扣除积分抵扣
					$scoredkmoney = 0;
				}
				
				$leveldkmoney = $order['leveldk_money'] ?? 0;
				if($bset['leveldk_kouchu'] == 0){ //扣除积分抵扣
					$leveldkmoney = 0;
				}

				$totalmoney = $totalmoney - $scoredkmoney - $leveldkmoney;
                if($totalmoney > 0){
                    $platformMoney = $totalmoney * $binfo['feepercent'] * 0.01;
                    $totalmoney = $totalmoney - $platformMoney;
                }
                $isbusinesspay = Db::name('payorder')->where('aid',$aid)->where('ordernum',$order['ordernum'])->value('isbusinesspay');
				if(!$isbusinesspay){
					if($totalmoney < 0){
						$bmoney = Db::name('business')->where('aid',$aid)->where('id',$order['bid'])->value('money');
						if($bmoney + $totalmoney < 0){
							return ['status'=>0,'msg'=>'操作失败,商家余额不足'];
						}
					}
					\app\common\Business::addmoney($aid,$order['bid'],$totalmoney,'货款，团购订单号：'.$order['ordernum'],true,$type,$order['ordernum'],['platformMoney'=>$platformMoney,'business_lirun'=>$business_lirun]);
				}else{
                	//商家推荐分成
					if($totalmoney > 0){
						if(getcustom('business_agent')){
							\app\common\Business::addparentcommission2($aid,$order['bid'],$totalmoney,$platformMoney,$business_lirun);
						}else{
							\app\common\Business::addparentcommission($aid,$order['bid'],$totalmoney);
						}
					}
                }
                //店铺加销量
                Db::name('business')->where('aid',$aid)->where('id',$order['bid'])->inc('sales',$order['num'])->update();
				
				if(getcustom('business_canuseplatcoupon') && $order['coupon_money'] > 0 && $order['coupon_rid'] > 0){
					$couponrecord = Db::name('coupon_record')->where('id',$order['coupon_rid'])->find();
					if($couponrecord && $couponrecord['bid'] == 0){
						$businessuserecord = [];
						$businessuserecord['aid'] = $order['aid'];
						$businessuserecord['bid'] = $order['bid'];
						$businessuserecord['mid'] = $order['mid'];
						$businessuserecord['ordertype'] = $type;
						$businessuserecord['orderid'] = $order['id'];
						$businessuserecord['couponrid'] = $order['coupon_rid'];
						$businessuserecord['couponid'] = $couponrecord['couponid'];
						$businessuserecord['couponname'] = $couponrecord['couponname'];
						$businessuserecord['couponmoney'] = $couponrecord['money'];
						$businessuserecord['decmoney'] = $order['coupon_money'];
						$businessuserecord['status'] = 1;
						$businessuserecord['createtime'] = time();
						Db::name('coupon_businessuserecord')->insert($businessuserecord);
						Db::name('business')->where('id',$order['bid'])->inc('couponmoney',$order['coupon_money'])->update();
					}
				}
            }
        }elseif($type=='kecheng'){
			if($order['bid']!=0){//入驻商家的货款

				$binfo = Db::name('business')->where('aid',$aid)->where('id',$order['bid'])->find();
				$totalcommission = 0;
				//if($order['iscommission']){
				if($order['parent1'] && $order['parent1commission'] > 0){
					$totalcommission += $order['parent1commission'];
				}
				if($order['parent2'] && $order['parent2commission'] > 0){
					$totalcommission += $order['parent2commission'];
				}
				if($order['parent3'] && $order['parent3commission'] > 0){
					$totalcommission += $order['parent3commission'];
				}
				//}
				$binfo = Db::name('business')->where('aid',$aid)->where('id',$order['bid'])->find();
				$bset = Db::name('business_sysset')->where('aid',$aid)->find();
				if($bset['commission_kouchu'] == 0){ //不扣除佣金
					$totalcommission = 0;
				}

				$totalmoney = $order['totalprice'] - $totalcommission;
				if($totalmoney > 0){
                    $platformMoney = $totalmoney * $binfo['feepercent'] * 0.01;
                    $totalmoney = $totalmoney - $platformMoney;
				}
				$isbusinesspay = Db::name('payorder')->where('aid',$aid)->where('ordernum',$order['ordernum'])->value('isbusinesspay');
				if(!$isbusinesspay){
					if($totalmoney < 0){
						$bmoney = Db::name('business')->where('aid',$aid)->where('id',$order['bid'])->value('money');
						if($bmoney + $totalmoney < 0){
							return ['status'=>0,'msg'=>'操作失败,商家余额不足'];
						}
					}
					\app\common\Business::addmoney($aid,$order['bid'],$totalmoney,'课程订单号：'.$order['ordernum'],true,$type,$order['ordernum'],['platformMoney'=>$platformMoney]);
				}else{
                	//商家推荐分成
					if($totalmoney > 0){
						if(getcustom('business_agent')){
							\app\common\Business::addparentcommission2($aid,$order['bid'],$totalmoney,$platformMoney);
						}else{
							\app\common\Business::addparentcommission($aid,$order['bid'],$totalmoney);
						}
					}
                }
				//店铺加销量
                if(empty($order['num'])){
                    $order['num'] = 1;
                }
				Db::name('business')->where('aid',$aid)->where('id',$order['bid'])->inc('sales',$order['num'])->update();
			}
		}elseif($type=='yueke'){
			if($order['bid']!=0){//入驻商家的货款

				$binfo = Db::name('business')->where('aid',$aid)->where('id',$order['bid'])->find();
				$totalmoney = $order['product_price'];
				if($totalmoney > 0){
                    $platformMoney = $totalmoney * $binfo['feepercent'] * 0.01;
                    $totalmoney = $totalmoney - $platformMoney;
				}
				$isbusinesspay = Db::name('payorder')->where('aid',$aid)->where('ordernum',$order['ordernum'])->value('isbusinesspay');
				if(!$isbusinesspay){
					if($totalmoney < 0){
						$bmoney = Db::name('business')->where('aid',$aid)->where('id',$order['bid'])->value('money');
						if($bmoney + $totalmoney < 0){
							return ['status'=>0,'msg'=>'操作失败,商家余额不足'];
						}
					}
					$worker = Db::name('yuyue_worker')->where('id',$order['workerid'])->find();
					\app\common\Business::addmoney($aid,$order['bid'],$totalmoney,'约课订单/('.$worker['realname'].')'.$worker['tel'].' /:'.$order['ordernum'],true,$type,$order['ordernum'],['platformMoney'=>$platformMoney]);
				}else{
                	//商家推荐分成
					if($totalmoney > 0){
						if(getcustom('business_agent')){
							\app\common\Business::addparentcommission2($aid,$order['bid'],$totalmoney,$platformMoney);
						}else{
							\app\common\Business::addparentcommission($aid,$order['bid'],$totalmoney);
						}
					}
                }
				//店铺加销量
				Db::name('business')->where('aid',$aid)->where('id',$order['bid'])->inc('sales',$order['num'])->update();
			}
		}elseif($type=='gift_bag'){
			if(getcustom('extend_gift_bag')){
				if($order['bid']!=0){//入驻商家的货款
					$binfo = Db::name('business')->where('aid',$aid)->where('id',$order['bid'])->find();
					$totalmoney = $order['totalprice'];
					if($totalmoney > 0){
                        $platformMoney = $totalmoney * $binfo['feepercent'] * 0.01;
                        $totalmoney = $totalmoney - $platformMoney;
					}
					$isbusinesspay = Db::name('payorder')->where('aid',$aid)->where('ordernum',$order['ordernum'])->value('isbusinesspay');
					if(!$isbusinesspay){
						\app\common\Business::addmoney($aid,$order['bid'],$totalmoney,'礼包订单号：'.$order['ordernum'],true,$type,$order['ordernum'],['platformMoney'=>$platformMoney]);
					}else{
	                	//商家推荐分成
						if($totalmoney > 0){
							if(getcustom('business_agent')){
								\app\common\Business::addparentcommission2($aid,$order['bid'],$totalmoney,$platformMoney);
							}else{
								\app\common\Business::addparentcommission($aid,$order['bid'],$totalmoney);
							}
						}
	                }
				}
			}
		}
		$set = Db::name('admin_set')->where('aid',$aid)->find();
		if($set['fxjiesuantime_delaydays'] == '0'){ //确认收货后发佣金 0天结算
			self::giveCommission($order,$type);
		}
        if(getcustom('business_fenxiao')){
            $fenxiao_type = $set['business_fenxiao_type'];
            //收货完成，店铺分销统计日营业额
            if($fenxiao_type==1){
                $payorder = Db::name('payorder')
                    ->where('orderid',$order['id'])
                    ->where('mid',$order['mid'])
                    ->where('status',1)
                    ->where('type',$type)
                    ->find();
                \app\common\Business::countBusinessYeji($payorder);
            }
        }
        \app\model\Payorder::afterusecoupon($order['id'],$type,2,$order['ordernum']);
        return ['status'=>1,'msg'=>'操作成功'];
	}

	//结算佣金 设置了延时结算时每小时执行
	public static function jiesuanCommission($aid,$admin_set=[]){
		if(getcustom('fxjiesuantime_perweek')) return;
        if(empty($admin_set))
            $admin_set = Db::name('admin_set')->where('aid',$aid)->find();
        $where = [];
        $where[] = ['aid', '=', $aid];
        $where[] = ['status', '=', 0];
        $where[] = ['type', 'in', ['shop','seckill','scoreshop','collage','lucky_collage','kecheng','tuangou']];
        if($admin_set['fxjiesuantime_delaydays'] > 0){
            $delaytime = floatval($admin_set['fxjiesuantime_delaydays']) * 86400;
            $dtime = time() - $delaytime;
            $where[] = ['createtime', '<', $dtime];
            $where[] = ['createtime', '>', $dtime-300*86400];//部分客户很长时间未收货，改为300天
        }else{
            $where[] = ['createtime', '<', time()];
        }
        $recordList = Db::name('member_commission_record')->where($where)->select()->toArray();
		foreach($recordList as $k=>$record){
			$order = Db::name($record['type'].'_order')->where('id',$record['orderid'])->find();
			if(!$order || $order['status'] == 4){
				Db::name('member_commission_record')->where('id',$record['id'])->update(['status'=>2]);
				continue;
			}
			$status = $order['status'];
			if($record['type'] == 'kecheng' && $status == 1) $status = 3;
			if(($admin_set['fxjiesuantime'] == 0 && $status==3 && $order['paytime'] < $dtime) || ($admin_set['fxjiesuantime'] == 1 && in_array($status,[1,2,3]) && $order['paytime'] < $dtime)){
				self::giveCommission($order,$record['type']);
			}
		}
	}
	//结算佣金 每周几结算
	public static function jiesuanCommissionWeek($aid,$admin_set=[]){
		if(!getcustom('fxjiesuantime_perweek')) return;
        if(empty($admin_set))
            $admin_set = Db::name('admin_set')->where('aid',$aid)->find();
		$week = $admin_set['fxjiesuantime_delaydays'];
		if($week == 0) return;
		if($week == 7) $week = 0;
		if($week != date('w')) return;
		$dtime = strtotime(date('Y-m-d',time()-86400));
		$recordList = Db::name('member_commission_record')->where('aid',$aid)->where('status',0)->where('type','in',['shop','seckill','scoreshop','collage','lucky_collage','kecheng','tuangou'])->where('createtime','<',$dtime)->where('createtime','>',$dtime-30*86400)->select()->toArray();
		foreach($recordList as $k=>$record){
			$order = Db::name($record['type'].'_order')->where('id',$record['orderid'])->find();
			if(!$order || $order['status'] == 4){
				Db::name('member_commission_record')->where('id',$record['id'])->update(['status'=>2]);
				continue;
			}
			$status = $order['status'];
			if($record['type'] == 'kecheng' && $status == 1) $status = 3;
			if(getcustom('commission_times_coupon')){
                if($record['type'] == 'coupon' && $status == 1) $status = 3;
            }
			if(($admin_set['fxjiesuantime'] == 0 && $status==3 && $order['paytime'] < $dtime) || ($admin_set['fxjiesuantime'] == 1 && in_array($status,[1,2,3]) && $order['paytime'] < $dtime)){
				self::giveCommission($order,$record['type']);
			}
		}
	}

	//发放佣金
	public static function giveCommission($order,$type='shop'){
		$aid = $order['aid'];
		if($type == 'shop'){
			$commission_record_list = Db::name('member_commission_record')->where('aid',$aid)->where('type','shop')->where('orderid',$order['id'])->where('status',0)->select();
			foreach($commission_record_list as $commission_record){
				Db::name('member_commission_record')->where('id',$commission_record['id'])->update(['status'=>1,'endtime'=>time()]);
				$og = Db::name('shop_order_goods')->where('id',$commission_record['ogid'])->find();
				Db::name('shop_order_goods')->where('id',$commission_record['ogid'])->update(['iscommission'=>1]);
				if($commission_record['commission'] > 0){
					$commission = $commission_record['commission'];
					if(getcustom('commission2moneypercent')){
						$sysset = Db::name('admin_set')->where('aid',$aid)->find();
						if($sysset['commission2moneypercent1'] > 0){
							//是否是首单
							$beforeorder = Db::name('shop_order')->where('aid',$aid)->where('mid',$order['mid'])->where('status','in','1,2,3')->where('paytime','<',$order['paytime'])->find();
							if(!$beforeorder){
								$commission = (100 - $sysset['commission2moneypercent1']) * $commission_record['commission'] * 0.01;
								$money = $sysset['commission2moneypercent1'] * $commission_record['commission'] * 0.01;
							}else{
								$commission = (100 - $sysset['commission2moneypercent2']) * $commission_record['commission'] * 0.01;
								$money = $sysset['commission2moneypercent2'] * $commission_record['commission'] * 0.01;
							}
							$commission = round($commission,2);
							$money = round($money,2);
							if($money > 0){
								\app\common\Member::addmoney($aid,$commission_record['mid'],$money,$commission_record['remark']);
							}
						}
					}
					\app\common\Member::addcommission($aid,$commission_record['mid'],$commission_record['frommid'],$commission,$commission_record['remark']);
					$tmplcontent = [];
					$tmplcontent['first'] = '恭喜您，成功分销商品获得'.t('佣金').'：￥'.$commission_record['commission'];
					$tmplcontent['remark'] = '点击进入查看~';
					$tmplcontent['keyword1'] = $og['name']; //商品信息
					$tmplcontent['keyword2'] = (string) $og['sell_price'];//商品单价
					$tmplcontent['keyword3'] = $commission_record['commission'].'元';//商品佣金
					$tmplcontent['keyword4'] = date('Y-m-d H:i:s',$commission_record['createtime']);//分销时间
					$rs = \app\common\Wechat::sendtmpl($aid,$commission_record['mid'],'tmpl_fenxiaosuccess',$tmplcontent,m_url('pages/my/usercenter', $aid));
                    //短信通知
					$tel = Db::name('member')->where('id',$commission_record['mid'])->value('tel');
                    $rs = \app\common\Sms::send($aid,$tel,'tmpl_fenxiaosuccess',['money'=>$commission_record['commission']]);
                    //发放团队收益
                    //根据分红奖团队收益
                    if(getcustom('teamfenhong_shouyi')){
                        $sysset = Db::name('admin_set')->where('aid',$aid)->find();
                        $midfhArr = [
                            $commission_record['mid']=>[
                                'commission' => $commission
                            ]
                        ];
                       \app\common\Fenhong::teamshouyi($aid,$sysset,$midfhArr,[],0,0,1,0);
                    }
				}
				if($commission_record['score'] > 0){
					\app\common\Member::addscore($aid,$commission_record['mid'],$commission_record['score'],$commission_record['remark']);
					$tmplcontent = [];
                    $tmplcontent['first'] = '恭喜您，成功分销商品获得：'.$commission_record['score'].t('积分');
                    $tmplcontent['remark'] = '点击进入查看~';
                    $tmplcontent['keyword1'] = $og['name']; //商品信息
                    $tmplcontent['keyword2'] = (string) $og['sell_price'];//商品单价
                    $tmplcontent['keyword3'] = $commission_record['score'].t('积分');//商品佣金
                    $tmplcontent['keyword4'] = date('Y-m-d H:i:s',$commission_record['createtime']);//分销时间
                    $rs = \app\common\Wechat::sendtmpl($aid,$commission_record['mid'],'tmpl_fenxiaosuccess',$tmplcontent,m_url('pages/my/usercenter', $aid));
                    //短信通知
					//$tel = Db::name('member')->where('id',$commission_record['mid'])->value('tel');
                    //$rs = \app\common\Sms::send($aid,$tel,'tmpl_fenxiaosuccess');
				}
			}
        }elseif($type=='seckill'){
			$commission_record_list = Db::name('member_commission_record')->where('aid',$aid)->where('type','seckill')->where('orderid',$order['id'])->where('status',0)->select();
			foreach($commission_record_list as $commission_record){
				Db::name('member_commission_record')->where('id',$commission_record['id'])->update(['status'=>1,'endtime'=>time()]);
				if($commission_record['commission'] > 0){
					\app\common\Member::addcommission($aid,$commission_record['mid'],$commission_record['frommid'],$commission_record['commission'],$commission_record['remark']);
					$tmplcontent = [];
					$tmplcontent['first'] = '恭喜您，成功分销商品获得'.t('佣金').'：￥'.$commission_record['commission'];
					$tmplcontent['remark'] = '点击进入查看~';
					$tmplcontent['keyword1'] = $order['proname']; //商品信息
					$tmplcontent['keyword2'] = (string) $order['sell_price'];//商品单价
					$tmplcontent['keyword3'] = $commission_record['commission'].'元';//商品佣金
					$tmplcontent['keyword4'] = date('Y-m-d H:i:s',$commission_record['createtime']);//分销时间
					$rs = \app\common\Wechat::sendtmpl($aid,$commission_record['mid'],'tmpl_fenxiaosuccess',$tmplcontent,m_url('pages/my/usercenter', $aid));
                    //短信通知
					$tel = Db::name('member')->where('id',$commission_record['mid'])->value('tel');
                    $rs = \app\common\Sms::send($aid,$tel,'tmpl_fenxiaosuccess',['money'=>$commission_record['commission']]);
                    //根据分红奖团队收益
                    if(getcustom('teamfenhong_shouyi')){
                        $sysset = Db::name('admin_set')->where('aid',$aid)->find();
                        $midfhArr = [
                            $commission_record['mid']=>[
                                'commission' => $commission_record['commission']
                            ]
                        ];
                       \app\common\Fenhong::teamshouyi($aid,$sysset,$midfhArr,[],0,0,1,0);
                    }
				}
				if($commission_record['score'] > 0){
					\app\common\Member::addscore($aid,$commission_record['mid'],$commission_record['score'],$commission_record['remark']);
					$tmplcontent = [];
                    $tmplcontent['first'] = '恭喜您，成功分销商品获得：'.$commission_record['score'].t('积分');
                    $tmplcontent['remark'] = '点击进入查看~';
                    $tmplcontent['keyword1'] = $order['proname']; //商品信息
                    $tmplcontent['keyword2'] = (string) $order['sell_price'];//商品单价
                    $tmplcontent['keyword3'] = $commission_record['score'].t('积分');//商品佣金
                    $tmplcontent['keyword4'] = date('Y-m-d H:i:s',$commission_record['createtime']);//分销时间
                    $rs = \app\common\Wechat::sendtmpl($aid,$commission_record['mid'],'tmpl_fenxiaosuccess',$tmplcontent,m_url('pages/my/usercenter', $aid));
                    //短信通知
					//$tel = Db::name('member')->where('id',$commission_record['mid'])->value('tel');
                    //$rs = \app\common\Sms::send($aid,$tel,'tmpl_fenxiaosuccess');
				}
			}
		}elseif($type == 'scoreshop'){
            //佣金
            $commission_record_list = Db::name('member_commission_record')->where('aid',$aid)->where('type',$type)->where('orderid',$order['id'])->where('status',0)->select();
            foreach($commission_record_list as $commission_record){
                Db::name('member_commission_record')->where('id',$commission_record['id'])->update(['status'=>1,'endtime'=>time()]);
                $og = Db::name($type.'_order_goods')->where('id',$commission_record['ogid'])->find();
                Db::name($type.'_order_goods')->where('id',$commission_record['ogid'])->update(['iscommission'=>1]);
                if($commission_record['commission'] > 0){
                    \app\common\Member::addcommission($aid,$commission_record['mid'],$commission_record['frommid'],$commission_record['commission'],$commission_record['remark']);
                    $tmplcontent = [];
                    $tmplcontent['first'] = '恭喜您，成功分销商品获得'.t('佣金').'：￥'.$commission_record['commission'];
                    $tmplcontent['remark'] = '点击进入查看~';
                    $tmplcontent['keyword1'] = $og['name']; //商品信息
                    $tmplcontent['keyword2'] = (string) $og['sell_price'];//商品单价
                    $tmplcontent['keyword3'] = $commission_record['commission'].'元';//商品佣金
                    $tmplcontent['keyword4'] = date('Y-m-d H:i:s',$commission_record['createtime']);//分销时间
                    $rs = \app\common\Wechat::sendtmpl($aid,$commission_record['mid'],'tmpl_fenxiaosuccess',$tmplcontent,m_url('pages/my/usercenter', $aid));
                    //短信通知
                    $tel = Db::name('member')->where('id',$commission_record['mid'])->value('tel');
                    $rs = \app\common\Sms::send($aid,$tel,'tmpl_fenxiaosuccess',['money'=>$commission_record['commission']]);
                    //根据分红奖团队收益
                    if(getcustom('teamfenhong_shouyi')){
                        $sysset = Db::name('admin_set')->where('aid',$aid)->find();
                        $midfhArr = [
                            $commission_record['mid']=>[
                                'commission' => $commission_record['commission']
                            ]
                        ];
                       \app\common\Fenhong::teamshouyi($aid,$sysset,$midfhArr,[],0,0,1,0);
                    }
                }
                if($commission_record['score'] > 0){
                    \app\common\Member::addscore($aid,$commission_record['mid'],$commission_record['score'],$commission_record['remark']);
                    $tmplcontent = [];
                    $tmplcontent['first'] = '恭喜您，成功分销商品获得：'.$commission_record['score'].t('积分');
                    $tmplcontent['remark'] = '点击进入查看~';
                    $tmplcontent['keyword1'] = $og['name']; //商品信息
                    $tmplcontent['keyword2'] = $og['sell_price'];//商品单价
                    $tmplcontent['keyword3'] = $commission_record['score'].t('积分');//商品佣金
                    $tmplcontent['keyword4'] = date('Y-m-d H:i:s',$commission_record['createtime']);//分销时间
                    $rs = \app\common\Wechat::sendtmpl($aid,$commission_record['mid'],'tmpl_fenxiaosuccess',$tmplcontent,m_url('pages/my/usercenter', $aid));
                    //短信通知
                    //$tel = Db::name('member')->where('id',$commission_record['mid'])->value('tel');
                    //$rs = \app\common\Sms::send($aid,$tel,'tmpl_fenxiaosuccess');
                }
            }
        }elseif($type == 'collage'){
            //佣金
            $commission_record_list = Db::name('member_commission_record')->where('aid',$aid)->where('type',$type)->where('orderid',$order['id'])->where('status',0)->select();
            foreach($commission_record_list as $commission_record){
                Db::name('member_commission_record')->where('id',$commission_record['id'])->update(['status'=>1,'endtime'=>time()]);
                $og = Db::name($type.'_order')->where('id',$commission_record['orderid'])->find();
                if($commission_record['commission'] > 0){
                    \app\common\Member::addcommission($aid,$commission_record['mid'],$commission_record['frommid'],$commission_record['commission'],$commission_record['remark']);
                    $tmplcontent = [];
                    $tmplcontent['first'] = '恭喜您，成功分销商品获得'.t('佣金').'：￥'.$commission_record['commission'];
                    $tmplcontent['remark'] = '点击进入查看~';
                    $tmplcontent['keyword1'] = $og['proname']; //商品信息
                    $tmplcontent['keyword2'] = $og['sell_price'];//商品单价
                    $tmplcontent['keyword3'] = $commission_record['commission'].'元';//商品佣金
                    $tmplcontent['keyword4'] = date('Y-m-d H:i:s',$commission_record['createtime']);//分销时间
                    $rs = \app\common\Wechat::sendtmpl($aid,$commission_record['mid'],'tmpl_fenxiaosuccess',$tmplcontent,m_url('pages/my/usercenter', $aid));
                    //短信通知
                    $tel = Db::name('member')->where('id',$commission_record['mid'])->value('tel');
                    $rs = \app\common\Sms::send($aid,$tel,'tmpl_fenxiaosuccess',['money'=>$commission_record['commission']]);
                    //根据分红奖团队收益
                    if(getcustom('teamfenhong_shouyi')){
                        $sysset = Db::name('admin_set')->where('aid',$aid)->find();
                        $midfhArr = [
                            $commission_record['mid']=>[
                                'commission' => $commission_record['commission']
                            ]
                        ];
                       \app\common\Fenhong::teamshouyi($aid,$sysset,$midfhArr,[],0,0,1,0);
                    }
                }
                if($commission_record['score'] > 0){
                    \app\common\Member::addscore($aid,$commission_record['mid'],$commission_record['score'],$commission_record['remark']);
                    $tmplcontent = [];
                    $tmplcontent['first'] = '恭喜您，成功分销商品获得：'.$commission_record['score'].t('积分');
                    $tmplcontent['remark'] = '点击进入查看~';
                    $tmplcontent['keyword1'] = $og['proname']; //商品信息
                    $tmplcontent['keyword2'] = $og['sell_price'];//商品单价
                    $tmplcontent['keyword3'] = $commission_record['score'].t('积分');//商品佣金
                    $tmplcontent['keyword4'] = date('Y-m-d H:i:s',$commission_record['createtime']);//分销时间
                    $rs = \app\common\Wechat::sendtmpl($aid,$commission_record['mid'],'tmpl_fenxiaosuccess',$tmplcontent,m_url('pages/my/usercenter', $aid));
                    //短信通知
                    //$tel = Db::name('member')->where('id',$commission_record['mid'])->value('tel');
                    //$rs = \app\common\Sms::send($aid,$tel,'tmpl_fenxiaosuccess');
                }
            }
        }elseif($type == 'kanjia'){
            //佣金
            $commission_record_list = Db::name('member_commission_record')->where('aid',$aid)->where('type',$type)->where('orderid',$order['id'])->where('status',0)->select();
            foreach($commission_record_list as $commission_record){
                Db::name('member_commission_record')->where('id',$commission_record['id'])->update(['status'=>1,'endtime'=>time()]);
                $og = Db::name($type.'_order')->where('id',$commission_record['orderid'])->find();
                if($commission_record['commission'] > 0){
                    \app\common\Member::addcommission($aid,$commission_record['mid'],$commission_record['frommid'],$commission_record['commission'],$commission_record['remark']);
                    $tmplcontent = [];
                    $tmplcontent['first'] = '恭喜您，成功分销商品获得'.t('佣金').'：￥'.$commission_record['commission'];
                    $tmplcontent['remark'] = '点击进入查看~';
                    $tmplcontent['keyword1'] = $og['proname']; //商品信息
                    $tmplcontent['keyword2'] = $og['product_price'];//商品单价
                    $tmplcontent['keyword3'] = $commission_record['commission'].'元';//商品佣金
                    $tmplcontent['keyword4'] = date('Y-m-d H:i:s',$commission_record['createtime']);//分销时间
                    $rs = \app\common\Wechat::sendtmpl($aid,$commission_record['mid'],'tmpl_fenxiaosuccess',$tmplcontent,m_url('pages/my/usercenter', $aid));
                    //短信通知
                    $tel = Db::name('member')->where('id',$commission_record['mid'])->value('tel');
                    $rs = \app\common\Sms::send($aid,$tel,'tmpl_fenxiaosuccess',['money'=>$commission_record['commission']]);
                    //根据分红奖团队收益
                    if(getcustom('teamfenhong_shouyi')){
                        $sysset = Db::name('admin_set')->where('aid',$aid)->find();
                        $midfhArr = [
                            $commission_record['mid']=>[
                                'commission' => $commission_record['commission']
                            ]
                        ];
                       \app\common\Fenhong::teamshouyi($aid,$sysset,$midfhArr,[],0,0,1,0);
                    }
                }
                if($commission_record['score'] > 0){
                    \app\common\Member::addscore($aid,$commission_record['mid'],$commission_record['score'],$commission_record['remark']);
                    $tmplcontent = [];
                    $tmplcontent['first'] = '恭喜您，成功分销商品获得：'.$commission_record['score'].t('积分');
                    $tmplcontent['remark'] = '点击进入查看~';
                    $tmplcontent['keyword1'] = $og['proname']; //商品信息
                    $tmplcontent['keyword2'] = $og['product_price'];//商品单价
                    $tmplcontent['keyword3'] = $commission_record['score'].t('积分');//商品佣金
                    $tmplcontent['keyword4'] = date('Y-m-d H:i:s',$commission_record['createtime']);//分销时间
                    $rs = \app\common\Wechat::sendtmpl($aid,$commission_record['mid'],'tmpl_fenxiaosuccess',$tmplcontent,m_url('pages/my/usercenter', $aid));
                    //短信通知
                    //$tel = Db::name('member')->where('id',$commission_record['mid'])->value('tel');
                    //$rs = \app\common\Sms::send($aid,$tel,'tmpl_fenxiaosuccess');
                }
            }
        }elseif($type == 'lucky_collage'){
            //佣金
            $commission_record_list = Db::name('member_commission_record')->where('aid',$aid)->where('type',$type)->where('orderid',$order['id'])->where('status',0)->select();
            foreach($commission_record_list as $commission_record){
				Db::name('member_commission_record')->where('id',$commission_record['id'])->update(['status'=>1,'endtime'=>time()]);
                $og = Db::name($type.'_order')->where('id',$commission_record['orderid'])->find();
                if($commission_record['commission'] > 0){
                    \app\common\Member::addcommission($aid,$commission_record['mid'],$commission_record['frommid'],$commission_record['commission'],$commission_record['remark']);
                    $tmplcontent = [];
                    $tmplcontent['first'] = '恭喜您，成功分销商品获得'.t('佣金').'：￥'.$commission_record['commission'];
                    $tmplcontent['remark'] = '点击进入查看~';
                    $tmplcontent['keyword1'] = $og['proname']; //商品信息
                    $tmplcontent['keyword2'] = $og['sell_price'];//商品单价
                    $tmplcontent['keyword3'] = $commission_record['commission'].'元';//商品佣金
                    $tmplcontent['keyword4'] = date('Y-m-d H:i:s',$commission_record['createtime']);//分销时间
                    $rs = \app\common\Wechat::sendtmpl($aid,$commission_record['mid'],'tmpl_fenxiaosuccess',$tmplcontent,m_url('pages/my/usercenter', $aid));
                    //短信通知
                    $tel = Db::name('member')->where('id',$commission_record['mid'])->value('tel');
                    $rs = \app\common\Sms::send($aid,$tel,'tmpl_fenxiaosuccess',['money'=>$commission_record['commission']]);
                    //根据分红奖团队收益
                    if(getcustom('teamfenhong_shouyi')){
                        $sysset = Db::name('admin_set')->where('aid',$aid)->find();
                        $midfhArr = [
                            $commission_record['mid']=>[
                                'commission' => $commission_record['commission']
                            ]
                        ];
                       \app\common\Fenhong::teamshouyi($aid,$sysset,$midfhArr,[],0,0,1,0);
                    }
                }
                if($commission_record['score'] > 0){
                    \app\common\Member::addscore($aid,$commission_record['mid'],$commission_record['score'],$commission_record['remark']);
                    $tmplcontent = [];
                    $tmplcontent['first'] = '恭喜您，成功分销商品获得：'.$commission_record['score'].t('积分');
                    $tmplcontent['remark'] = '点击进入查看~';
                    $tmplcontent['keyword1'] = $og['proname']; //商品信息
                    $tmplcontent['keyword2'] = $og['sell_price'];//商品单价
                    $tmplcontent['keyword3'] = $commission_record['score'].t('积分');//商品佣金
                    $tmplcontent['keyword4'] = date('Y-m-d H:i:s',$commission_record['createtime']);//分销时间
                    $rs = \app\common\Wechat::sendtmpl($aid,$commission_record['mid'],'tmpl_fenxiaosuccess',$tmplcontent,m_url('pages/my/usercenter', $aid));
                    //短信通知
                    //$tel = Db::name('member')->where('id',$commission_record['mid'])->value('tel');
                    //$rs = \app\common\Sms::send($aid,$tel,'tmpl_fenxiaosuccess');
                }

            }
        }elseif($type == 'kecheng'){
            //佣金
            $commission_record_list = Db::name('member_commission_record')->where('aid',$aid)->where('type',$type)->where('orderid',$order['id'])->where('status',0)->select();
            foreach($commission_record_list as $commission_record){
                Db::name('member_commission_record')->where('id',$commission_record['id'])->update(['status'=>1,'endtime'=>time()]);
                $og = Db::name($type.'_order')->where('id',$commission_record['orderid'])->find();
                if($commission_record['commission'] > 0){
                    \app\common\Member::addcommission($aid,$commission_record['mid'],$commission_record['frommid'],$commission_record['commission'],$commission_record['remark']);
                    $tmplcontent = [];
                    $tmplcontent['first'] = '恭喜您，成功分销商品获得'.t('佣金').'：￥'.$commission_record['commission'];
                    $tmplcontent['remark'] = '点击进入查看~';
                    $tmplcontent['keyword1'] = $og['proname']; //商品信息
                    $tmplcontent['keyword2'] = $og['price'];//商品单价
                    $tmplcontent['keyword3'] = $commission_record['commission'].'元';//商品佣金
                    $tmplcontent['keyword4'] = date('Y-m-d H:i:s',$commission_record['createtime']);//分销时间
                    $rs = \app\common\Wechat::sendtmpl($aid,$commission_record['mid'],'tmpl_fenxiaosuccess',$tmplcontent,m_url('pages/my/usercenter', $aid));
                    //短信通知
                    $tel = Db::name('member')->where('id',$commission_record['mid'])->value('tel');
                    $rs = \app\common\Sms::send($aid,$tel,'tmpl_fenxiaosuccess',['money'=>$commission_record['commission']]);
                    //根据分红奖团队收益
                    if(getcustom('teamfenhong_shouyi')){
                        $sysset = Db::name('admin_set')->where('aid',$aid)->find();
                        $midfhArr = [
                            $commission_record['mid']=>[
                                'commission' => $commission_record['commission']
                            ]
                        ];
                       \app\common\Fenhong::teamshouyi($aid,$sysset,$midfhArr,[],0,0,1,0);
                    }
                }
                if($commission_record['score'] > 0){
                    \app\common\Member::addscore($aid,$commission_record['mid'],$commission_record['score'],$commission_record['remark']);
                    $tmplcontent = [];
                    $tmplcontent['first'] = '恭喜您，成功分销商品获得：'.$commission_record['score'].t('积分');
                    $tmplcontent['remark'] = '点击进入查看~';
                    $tmplcontent['keyword1'] = $og['proname']; //商品信息
                    $tmplcontent['keyword2'] = $og['price'];//商品单价
                    $tmplcontent['keyword3'] = $commission_record['score'].t('积分');//商品佣金
                    $tmplcontent['keyword4'] = date('Y-m-d H:i:s',$commission_record['createtime']);//分销时间
                    $rs = \app\common\Wechat::sendtmpl($aid,$commission_record['mid'],'tmpl_fenxiaosuccess',$tmplcontent,m_url('pages/my/usercenter', $aid));
                    //短信通知
                    //$tel = Db::name('member')->where('id',$commission_record['mid'])->value('tel');
                    //$rs = \app\common\Sms::send($aid,$tel,'tmpl_fenxiaosuccess');
                }
            }
        }elseif($type=='tuangou'){
			$commission_record_list = Db::name('member_commission_record')->where('aid',$aid)->where('type',$type)->where('orderid',$order['id'])->where('status',0)->select();
			foreach($commission_record_list as $commission_record){
				Db::name('member_commission_record')->where('id',$commission_record['id'])->update(['status'=>1,'endtime'=>time()]);
				if($commission_record['commission'] > 0){
					\app\common\Member::addcommission($aid,$commission_record['mid'],$commission_record['frommid'],$commission_record['commission'],$commission_record['remark']);
					$tmplcontent = [];
					$tmplcontent['first'] = '恭喜您，成功分销商品获得'.t('佣金').'：￥'.$commission_record['commission'];
					$tmplcontent['remark'] = '点击进入查看~';
					$tmplcontent['keyword1'] = $order['proname']; //商品信息
					$tmplcontent['keyword2'] = (string) $order['sell_price'];//商品单价
					$tmplcontent['keyword3'] = $commission_record['commission'].'元';//商品佣金
					$tmplcontent['keyword4'] = date('Y-m-d H:i:s',$commission_record['createtime']);//分销时间
					$rs = \app\common\Wechat::sendtmpl($aid,$commission_record['mid'],'tmpl_fenxiaosuccess',$tmplcontent,m_url('pages/my/usercenter', $aid));
                    //短信通知
					$tel = Db::name('member')->where('id',$commission_record['mid'])->value('tel');
                    $rs = \app\common\Sms::send($aid,$tel,'tmpl_fenxiaosuccess',['money'=>$commission_record['commission']]);
                    //根据分红奖团队收益
                    if(getcustom('teamfenhong_shouyi')){
                        $sysset = Db::name('admin_set')->where('aid',$aid)->find();
                        $midfhArr = [
                            $commission_record['mid']=>[
                                'commission' => $commission_record['commission']
                            ]
                        ];
                       \app\common\Fenhong::teamshouyi($aid,$sysset,$midfhArr,[],0,0,1,0);
                    }
				}
				if($commission_record['score'] > 0){
					\app\common\Member::addscore($aid,$commission_record['mid'],$commission_record['score'],$commission_record['remark']);
					$tmplcontent = [];
                    $tmplcontent['first'] = '恭喜您，成功分销商品获得：'.$commission_record['score'].t('积分');
                    $tmplcontent['remark'] = '点击进入查看~';
                    $tmplcontent['keyword1'] = $order['proname']; //商品信息
                    $tmplcontent['keyword2'] = (string) $order['sell_price'];//商品单价
                    $tmplcontent['keyword3'] = $commission_record['score'].t('积分');//商品佣金
                    $tmplcontent['keyword4'] = date('Y-m-d H:i:s',$commission_record['createtime']);//分销时间
                    $rs = \app\common\Wechat::sendtmpl($aid,$commission_record['mid'],'tmpl_fenxiaosuccess',$tmplcontent,m_url('pages/my/usercenter', $aid));
                    //短信通知
					//$tel = Db::name('member')->where('id',$commission_record['mid'])->value('tel');
                    //$rs = \app\common\Sms::send($aid,$tel,'tmpl_fenxiaosuccess');
				}
			}
		}elseif($type == 'yuyue'){
            //佣金
            $commission_record_list = Db::name('member_commission_record')->where('aid',$aid)->where('type',$type)->where('orderid',$order['id'])->where('status',0)->select();
            foreach($commission_record_list as $commission_record){
				Db::name('member_commission_record')->where('id',$commission_record['id'])->update(['status'=>1,'endtime'=>time()]);
                $og = Db::name($type.'_order')->where('id',$commission_record['orderid'])->find();
                if($commission_record['commission'] > 0){
                    \app\common\Member::addcommission($aid,$commission_record['mid'],$commission_record['frommid'],$commission_record['commission'],$commission_record['remark']);
                    $tmplcontent = [];
                    $tmplcontent['first'] = '恭喜您，成功分销服务获得'.t('佣金').'：￥'.$commission_record['commission'];
                    $tmplcontent['remark'] = '点击进入查看~';
                    $tmplcontent['keyword1'] = $og['proname']; //商品信息
                    $tmplcontent['keyword2'] = $og['sell_price'];//商品单价
                    $tmplcontent['keyword3'] = $commission_record['commission'].'元';//商品佣金
                    $tmplcontent['keyword4'] = date('Y-m-d H:i:s',$commission_record['createtime']);//分销时间
                    $rs = \app\common\Wechat::sendtmpl($aid,$commission_record['mid'],'tmpl_fenxiaosuccess',$tmplcontent,m_url('pages/my/usercenter', $aid));
                    //短信通知
                    $tel = Db::name('member')->where('id',$commission_record['mid'])->value('tel');
                    $rs = \app\common\Sms::send($aid,$tel,'tmpl_fenxiaosuccess',['money'=>$commission_record['commission']]);
                    //根据分红奖团队收益
                    if(getcustom('teamfenhong_shouyi')){
                        $sysset = Db::name('admin_set')->where('aid',$aid)->find();
                        $midfhArr = [
                            $commission_record['mid']=>[
                                'commission' => $commission_record['commission']
                            ]
                        ];
                        \app\common\Fenhong::teamshouyi($aid,$sysset,$midfhArr,[],0,0,1,0);
                    }
                }
                if($commission_record['score'] > 0){
                    \app\common\Member::addscore($aid,$commission_record['mid'],$commission_record['score'],$commission_record['remark']);
                    $tmplcontent = [];
                    $tmplcontent['first'] = '恭喜您，成功分销服务获得：'.$commission_record['score'].t('积分');
                    $tmplcontent['remark'] = '点击进入查看~';
                    $tmplcontent['keyword1'] = $og['proname']; //商品信息
                    $tmplcontent['keyword2'] = $og['sell_price'];//商品单价
                    $tmplcontent['keyword3'] = $commission_record['score'].t('积分');//商品佣金
                    $tmplcontent['keyword4'] = date('Y-m-d H:i:s',$commission_record['createtime']);//分销时间
                    $rs = \app\common\Wechat::sendtmpl($aid,$commission_record['mid'],'tmpl_fenxiaosuccess',$tmplcontent,m_url('pages/my/usercenter', $aid));
                    //短信通知
                    //$tel = Db::name('member')->where('id',$commission_record['mid'])->value('tel');
                    //$rs = \app\common\Sms::send($aid,$tel,'tmpl_fenxiaosuccess');
                }

            }
        }elseif($type=='cashier'){
            //佣金
            $commission_record_list = Db::name('member_commission_record')->where('aid',$aid)->where('type',$type)->where('orderid',$order['id'])->where('status',0)->select();
            foreach($commission_record_list as $commission_record){
                Db::name('member_commission_record')->where('id',$commission_record['id'])->update(['status'=>1,'endtime'=>time()]);
                $og = Db::name($type.'_order')->where('id',$commission_record['orderid'])->find();
                if($commission_record['commission'] > 0){
                    \app\common\Member::addcommission($aid,$commission_record['mid'],$commission_record['frommid'],$commission_record['commission'],$commission_record['remark']);
                    $tmplcontent = [];
                    $tmplcontent['first'] = '恭喜您，成功分销服务获得'.t('佣金').'：￥'.$commission_record['commission'];
                    $tmplcontent['remark'] = '点击进入查看~';
                    $tmplcontent['keyword1'] = $og['proname']; //商品信息
                    $tmplcontent['keyword2'] = $og['sell_price'];//商品单价
                    $tmplcontent['keyword3'] = $commission_record['commission'].'元';//商品佣金
                    $tmplcontent['keyword4'] = date('Y-m-d H:i:s',$commission_record['createtime']);//分销时间
                    $rs = \app\common\Wechat::sendtmpl($aid,$commission_record['mid'],'tmpl_fenxiaosuccess',$tmplcontent,m_url('pages/my/usercenter', $aid));
                    //短信通知
                    $tel = Db::name('member')->where('id',$commission_record['mid'])->value('tel');
                    $rs = \app\common\Sms::send($aid,$tel,'tmpl_fenxiaosuccess',['money'=>$commission_record['commission']]);
                    //根据分红奖团队收益
                    if(getcustom('teamfenhong_shouyi')){
                        $sysset = Db::name('admin_set')->where('aid',$aid)->find();
                        $midfhArr = [
                            $commission_record['mid']=>[
                                'commission' => $commission_record['commission']
                            ]
                        ];
                       \app\common\Fenhong::teamshouyi($aid,$sysset,$midfhArr,[],0,0,1,0);
                    }
                }
                if($commission_record['score'] > 0){
                    \app\common\Member::addscore($aid,$commission_record['mid'],$commission_record['score'],$commission_record['remark']);
                    $tmplcontent = [];
                    $tmplcontent['first'] = '恭喜您，成功分销服务获得：'.$commission_record['score'].t('积分');
                    $tmplcontent['remark'] = '点击进入查看~';
                    $tmplcontent['keyword1'] = $og['proname']; //商品信息
                    $tmplcontent['keyword2'] = $og['sell_price'];//商品单价
                    $tmplcontent['keyword3'] = $commission_record['score'].t('积分');//商品佣金
                    $tmplcontent['keyword4'] = date('Y-m-d H:i:s',$commission_record['createtime']);//分销时间
                    $rs = \app\common\Wechat::sendtmpl($aid,$commission_record['mid'],'tmpl_fenxiaosuccess',$tmplcontent,m_url('pages/my/usercenter', $aid));
                    //短信通知
                    //$tel = Db::name('member')->where('id',$commission_record['mid'])->value('tel');
                    //$rs = \app\common\Sms::send($aid,$tel,'tmpl_fenxiaosuccess');
                }

            }
        }elseif($type=='restaurant_shop'){
            //佣金
            $commission_record_list = Db::name('member_commission_record')->where('aid',$aid)->where('type',$type)->where('orderid',$order['id'])->where('status',0)->select();
            foreach($commission_record_list as $commission_record){
                Db::name('member_commission_record')->where('id',$commission_record['id'])->update(['status'=>1,'endtime'=>time()]);
                $og = Db::name($type.'_order')->where('id',$commission_record['orderid'])->find();
                if($commission_record['commission'] > 0){
                    \app\common\Member::addcommission($aid,$commission_record['mid'],$commission_record['frommid'],$commission_record['commission'],$commission_record['remark']);
                    $tmplcontent = [];
                    $tmplcontent['first'] = '恭喜您，成功分销服务获得'.t('佣金').'：￥'.$commission_record['commission'];
                    $tmplcontent['remark'] = '点击进入查看~';
                    $tmplcontent['keyword1'] = $og['proname']; //商品信息
                    $tmplcontent['keyword2'] = $og['sell_price'];//商品单价
                    $tmplcontent['keyword3'] = $commission_record['commission'].'元';//商品佣金
                    $tmplcontent['keyword4'] = date('Y-m-d H:i:s',$commission_record['createtime']);//分销时间
                    $rs = \app\common\Wechat::sendtmpl($aid,$commission_record['mid'],'tmpl_fenxiaosuccess',$tmplcontent,m_url('pages/my/usercenter', $aid));
                    //短信通知
                    $tel = Db::name('member')->where('id',$commission_record['mid'])->value('tel');
                    $rs = \app\common\Sms::send($aid,$tel,'tmpl_fenxiaosuccess',['money'=>$commission_record['commission']]);
                    //根据分红奖团队收益
                    if(getcustom('teamfenhong_shouyi')){
                        $sysset = Db::name('admin_set')->where('aid',$aid)->find();
                        $midfhArr = [
                            $commission_record['mid']=>[
                                'commission' => $commission_record['commission']
                            ]
                        ];
                       \app\common\Fenhong::teamshouyi($aid,$sysset,$midfhArr,[],0,0,1,0);
                    }
                }
                if($commission_record['score'] > 0){
                    \app\common\Member::addscore($aid,$commission_record['mid'],$commission_record['score'],$commission_record['remark']);
                    $tmplcontent = [];
                    $tmplcontent['first'] = '恭喜您，成功分销服务获得：'.$commission_record['score'].t('积分');
                    $tmplcontent['remark'] = '点击进入查看~';
                    $tmplcontent['keyword1'] = $og['proname']; //商品信息
                    $tmplcontent['keyword2'] = $og['sell_price'];//商品单价
                    $tmplcontent['keyword3'] = $commission_record['score'].t('积分');//商品佣金
                    $tmplcontent['keyword4'] = date('Y-m-d H:i:s',$commission_record['createtime']);//分销时间
                    $rs = \app\common\Wechat::sendtmpl($aid,$commission_record['mid'],'tmpl_fenxiaosuccess',$tmplcontent,m_url('pages/my/usercenter', $aid));
                    //短信通知
                    //$tel = Db::name('member')->where('id',$commission_record['mid'])->value('tel');
                    //$rs = \app\common\Sms::send($aid,$tel,'tmpl_fenxiaosuccess');
                }
            }
        }elseif($type=='coupon'){
		    if(getcustom('commission_times_coupon')){
                //佣金
                $commission_record_list = Db::name('member_commission_record')->where('aid',$aid)->where('type',$type)->where('orderid',$order['id'])->where('status',0)->select();
                foreach($commission_record_list as $commission_record){
                    Db::name('member_commission_record')->where('id',$commission_record['id'])->update(['status'=>1,'endtime'=>time()]);
                    $og = Db::name($type.'_order')->where('id',$commission_record['orderid'])->find();
                    if($commission_record['commission'] > 0){
                        \app\common\Member::addcommission($aid,$commission_record['mid'],$commission_record['frommid'],$commission_record['commission'],$commission_record['remark']);
                        $tmplcontent = [];
                        $tmplcontent['first'] = '恭喜您，成功分销服务获得'.t('佣金').'：￥'.$commission_record['commission'];
                        $tmplcontent['remark'] = '点击进入查看~';
                        $tmplcontent['keyword1'] = $og['proname']; //商品信息
                        $tmplcontent['keyword2'] = $og['sell_price'];//商品单价
                        $tmplcontent['keyword3'] = $commission_record['commission'].'元';//商品佣金
                        $tmplcontent['keyword4'] = date('Y-m-d H:i:s',$commission_record['createtime']);//分销时间
                        $rs = \app\common\Wechat::sendtmpl($aid,$commission_record['mid'],'tmpl_fenxiaosuccess',$tmplcontent,m_url('pages/my/usercenter', $aid));
                        //短信通知
                        $tel = Db::name('member')->where('id',$commission_record['mid'])->value('tel');
                        $rs = \app\common\Sms::send($aid,$tel,'tmpl_fenxiaosuccess',['money'=>$commission_record['commission']]);
                    }
                    if($commission_record['score'] > 0){
                        \app\common\Member::addscore($aid,$commission_record['mid'],$commission_record['score'],$commission_record['remark']);
                        $tmplcontent = [];
                        $tmplcontent['first'] = '恭喜您，成功分销服务获得：'.$commission_record['score'].t('积分');
                        $tmplcontent['remark'] = '点击进入查看~';
                        $tmplcontent['keyword1'] = $og['proname']; //商品信息
                        $tmplcontent['keyword2'] = $og['sell_price'];//商品单价
                        $tmplcontent['keyword3'] = $commission_record['score'].t('积分');//商品佣金
                        $tmplcontent['keyword4'] = date('Y-m-d H:i:s',$commission_record['createtime']);//分销时间
                        $rs = \app\common\Wechat::sendtmpl($aid,$commission_record['mid'],'tmpl_fenxiaosuccess',$tmplcontent,m_url('pages/my/usercenter', $aid));
                        //短信通知
                        //$tel = Db::name('member')->where('id',$commission_record['mid'])->value('tel');
                        //$rs = \app\common\Sms::send($aid,$tel,'tmpl_fenxiaosuccess');
                    }

                } 
            }
           
        }elseif($type=='livepay'){
            if(getcustom('extend_chongzhi')){
			$commission_record_list = Db::name('member_commission_record')->where('aid',$aid)->where('type','livepay')->where('orderid',$order['id'])->where('status',0)->select();
			foreach($commission_record_list as $commission_record){
				Db::name('member_commission_record')->where('id',$commission_record['id'])->update(['status'=>1,'endtime'=>time()]);
				if($commission_record['commission'] > 0){
					\app\common\Member::addcommission($aid,$commission_record['mid'],$commission_record['frommid'],$commission_record['commission'],$commission_record['remark']);
					$tmplcontent = [];
					$tmplcontent['first'] = '恭喜您，成功生活缴费分销获得'.t('佣金').'：￥'.$commission_record['commission'];
					$tmplcontent['remark'] = '点击进入查看~';
					$tmplcontent['keyword1'] = $order['type_name']; //商品信息
					$tmplcontent['keyword2'] = (string) $order['pay_money'];//商品单价
					$tmplcontent['keyword3'] = $commission_record['commission'].'元';//商品佣金
					$tmplcontent['keyword4'] = date('Y-m-d H:i:s',$commission_record['createtime']);//分销时间
					$rs = \app\common\Wechat::sendtmpl($aid,$commission_record['mid'],'tmpl_fenxiaosuccess',$tmplcontent,m_url('pages/my/usercenter', $aid));
                    //短信通知
					$tel = Db::name('member')->where('id',$commission_record['mid'])->value('tel');
                    $rs = \app\common\Sms::send($aid,$tel,'tmpl_fenxiaosuccess',['money'=>$commission_record['commission']]);
				}
            }
			}
		}elseif($type=='gift_pack'){
            if(getcustom('yx_gift_pack')){
			$commission_record_list = Db::name('member_commission_record')->where('aid',$aid)->where('type','gift_pack')->where('orderid',$order['id'])->where('status',0)->select();
				foreach($commission_record_list as $commission_record){
					Db::name('member_commission_record')->where('id',$commission_record['id'])->update(['status'=>1,'endtime'=>time()]);
					if($commission_record['commission'] > 0){
						\app\common\Member::addcommission($aid,$commission_record['mid'],$commission_record['frommid'],$commission_record['commission'],$commission_record['remark']);
						$tmplcontent = [];
						$tmplcontent['first'] = '恭喜您，分销获得'.t('佣金').'：￥'.$commission_record['commission'];
						$tmplcontent['remark'] = '点击进入查看~';
						$tmplcontent['keyword1'] = $order['title']; 
						$tmplcontent['keyword2'] = (string) $order['sell_price'];
						$tmplcontent['keyword3'] = $commission_record['commission'].'元';
						$tmplcontent['keyword4'] = date('Y-m-d H:i:s',$commission_record['createtime']);//分销时间
						$rs = \app\common\Wechat::sendtmpl($aid,$commission_record['mid'],'tmpl_fenxiaosuccess',$tmplcontent,m_url('pages/my/usercenter', $aid));
						//短信通知
						$tel = Db::name('member')->where('id',$commission_record['mid'])->value('tel');
						$rs = \app\common\Sms::send($aid,$tel,'tmpl_fenxiaosuccess',['money'=>$commission_record['commission']]);
					}
				}
			}
		}

        if(getcustom('commission_butie')){
            $sysset = Db::name('admin_set')->where('aid',$aid)->find();
            $fx_butie_type = $sysset['fx_butie_type'];
            $fx_butie_circle = $sysset['fx_butie_circle'];
            //记录分销补贴
            $butie_ids = [];
            foreach($commission_record_list as $record){
                if($record['butie']<=0){
                    continue;
                }
                //记录补贴数据
                $data_butie = [];
                $data_butie['aid'] = $record['aid'];
                $data_butie['mid'] = $record['mid'];
                $data_butie['frommid'] = $record['frommid'];
                $data_butie['orderid'] = $record['orderid'];
                $data_butie['ogid'] = $record['ogid'];
                $data_butie['type'] = $record['type'];
                $data_butie['commission'] = $record['butie'];
                $data_butie['fx_butie_type'] = $fx_butie_type;
                $data_butie['fx_butie_circle'] = $fx_butie_circle;
                $data_butie['fx_butie_send_week'] = $sysset['fx_butie_send_week'];
                $data_butie['fx_butie_send_day'] = $sysset['fx_butie_send_day'];;
                $data_butie['createtime'] = time();
                $data_butie['record_id'] = $record['id'];
                $data_butie['remark'] = $record['remark'];
                $butie_id = Db::name('member_commission_butie')->insertGetId($data_butie);
                $butie_ids[] = $butie_id;
            }
            if($butie_ids){
                \app\common\Member::commission_butie($record['aid'],$butie_ids);
            }
        }

		return ['status'=>1,'msg'=>'操作成功'];
	}

    //重新计算分成
    public static function updateCommission($orderGoods, $refundOrderGoods)
    {
        $newkey = 'ogid';
        $refundOrderGoods = collect($refundOrderGoods)->dictionary(null,$newkey);
        $ogids = array_keys($refundOrderGoods);
        foreach ($orderGoods as $og) {
            if(in_array($og['id'], $ogids)) {
                $new = [];
                if($og['parent1'] && ($og['parent1commission'] || $og['parent1score'])) {
                    $record = [];
                    if($og['parent1commission']) {
                        $new['parent1commission'] = $og['parent1commission'] / $og['num'] * ($og['num'] - $og['refund_num']);
                        $record['commission'] = $new['parent1commission'];
                    }
                    if($og['parent1score']) {
                        $new['parent1score'] = $og['parent1score'] / $og['num'] * ($og['num'] - $og['refund_num']);
                        $record['score'] = $new['parent1score'];
                    }
                    if($record) {
                        Db::name('member_commission_record')->where('mid',$og['parent1'])->where('aid',$og['aid'])->where('orderid',$og['orderid'])
                            ->where('ogid', $og['id'])->where('type', 'shop')->update($record);
                    }
                }
                if($og['parent2'] && ($og['parent2commission'] || $og['parent2score'])) {
                    $record = [];
                    if($og['parent2commission']) {
                        $new['parent2commission'] = $og['parent2commission'] / $og['num'] * ($og['num'] - $og['refund_num']);
                        $record['commission'] = $new['parent2commission'];
                    }
                    if($og['parent2score']) {
                        $new['parent2score'] = $og['parent2score'] / $og['num'] * ($og['num'] - $og['refund_num']);
                        $record['score'] = $new['parent2score'];
                    }
                    if($record) {
                        Db::name('member_commission_record')->where('mid',$og['parent2'])->where('aid',$og['aid'])->where('orderid',$og['orderid'])
                            ->where('ogid', $og['id'])->where('type', 'shop')->update($record);
                    }
                }
                if($og['parent3'] && ($og['parent3commission'] || $og['parent3score'])) {
                    $record = [];
                    if($og['parent3commission']) {
                        $new['parent3commission'] = $og['parent3commission'] / $og['num'] * ($og['num'] - $og['refund_num']);
                        $record['commission'] = $new['parent3commission'];
                    }
                    if($og['parent3score']) {
                        $new['parent3score'] = $og['parent3score'] / $og['num'] * ($og['num'] - $og['refund_num']);
                        $record['score'] = $new['parent3score'];
                    }
                    if($record) {
                        Db::name('member_commission_record')->where('mid',$og['parent3'])->where('aid',$og['aid'])->where('orderid',$og['orderid'])
                            ->where('ogid', $og['id'])->where('type', 'shop')->update($record);
                    }
                }
                if($new)
                    Db::name('shop_order_goods')->where('id', $og['id'])->update($new);
            }
        }
    }

    //递归分销:按订单金额的50%[变量]一直向下分销，直到金额小于1[变量]元截止；
    public static function recursionCommission($aid,$mid=0,$totalprice=0,$orderid='',$ogid='',$type='shop'){
        if(getcustom('commission_recursion')) {
            if (empty($mid)) return;
            //所有的父级
            $adminset = Db::name('admin_set')->where('aid', $aid)->field('is_fugou_commission,fugou_recursion_percent,fugou_commission_min')->find();
            if (empty($adminset['is_fugou_commission']) || empty($adminset['fugou_recursion_percent'])) {
                return;
            }
            $commission_min = $adminset['fugou_commission_min'] ?? 0;
            $recursionPercent = $adminset['fugou_recursion_percent'];
            $rate = round(100 / $recursionPercent, 2);
            self::recursionCommissionAllParent($aid, $mid, $totalprice, $commission_min, $recursionPercent, $rate, $mid, $orderid, $ogid);
        }
    }

    //递归发佣金
    public static function recursionCommissionAllParent($aid,$mid,$totalprice,$commission_min,$recursionPercent,$rate=2,$frommid='',$orderid='',$ogid=''){
        if(getcustom('commission_recursion')) {
            if ($totalprice <= $commission_min) {
                return;
            }
            $commission = $totalprice * $recursionPercent * 0.01;
            if ($commission <= $commission_min) {
                return;
            }
            $member = Db::name('member')->where('aid', $aid)->where('id', $mid)->field('id,levelid,pid,path,path_origin')->find();
            if (empty($member['pid'])) return;
            $parent = Db::name('member')->alias('m')->join('member_level l', 'm.levelid=l.id')
                ->where('m.aid', $aid)
                ->where('m.id', $member['pid'])->field('m.id,m.levelid,m.pid,l.is_fugou_commission')->find();
            if ($parent['is_fugou_commission']) {
                Db::name('member_commission_record')->insert(['aid' => $aid, 'mid' => $parent['id'], 'frommid' => $frommid, 'orderid' => $orderid, 'ogid' => $ogid, 'type' => 'shop', 'commission' => $commission, 'score' => 0, 'remark' => '下级购物奖励[递归]', 'createtime' => time()]);
            }
            //如果有上级 继续发奖励
            if ($parent['pid'] > 0) {
                $recursionPercent = $recursionPercent / $rate;
                return self::recursionCommissionAllParent($aid, $parent['id'], $totalprice, $commission_min, $recursionPercent, $rate, $frommid, $orderid, $ogid);
            }
            return;
        }
    }

    //小程序 发货信息录入接口
    public static function wxShipping($aid,$order,$orderType = 'shop',$shippingInfo=[]){
        $isTradeManaged = \app\common\Wechat::isTradeManaged($aid);
        if($isTradeManaged['status'] == 1 && $isTradeManaged['is_trade_managed']){
            \think\facade\Log::write('wxShipping发货信息录入接口:'.jsonEncode($order));
            \think\facade\Log::write('wxShipping发货信息录入接口orderType:'.$orderType);
            \think\facade\Log::write('wxShipping发货信息录入接口shippingInfo:'.jsonEncode($shippingInfo));
            //发货信息录入接口 https://developers.weixin.qq.com/miniprogram/dev/platform-capabilities/business-capabilities/order-shipping/order-shipping.html#%E4%B8%80%E3%80%81%E5%8F%91%E8%B4%A7%E4%BF%A1%E6%81%AF%E5%BD%95%E5%85%A5%E6%8E%A5%E5%8F%A3
            $orderType = str_replace('_order','',$orderType);
            $wxpaylog = Db::name('wxpay_log')->where('aid',$aid)->where('ordernum',$order['ordernum'])->where('tablename',$orderType)->find();
            if(empty($wxpaylog)){
                \think\facade\Log::write('wxShipping发货信息录入接口:未找到微信支付记录');
                return ['status'=>0,'msg'=>'未找到微信支付记录'];
            }
            if($wxpaylog['platform'] != 'wx'){
                \think\facade\Log::write('wxShipping发货信息录入接口:非微信小程序支付订单');
                return ['status'=>0,'msg'=>'非微信小程序支付订单'];
            }
            //支付不足20秒不请求微信接口
            if($wxpaylog['createtime'] && time() - $wxpaylog['createtime'] < 20){
                $data = [
                    'aid'=>$aid,
                    'mid'=>$order['mid'],
                    'wxpaylogid'=>$wxpaylog['id'],
                    'openid'=>$wxpaylog['openid'],
                    'tablename'=>$wxpaylog['tablename'],
                    'ordernum'=>$wxpaylog['ordernum'],
                    'mch_id'=>$wxpaylog['mch_id'],
                    'createtime'=>time(),
                    'nexttime'=>time()+20,
                    'times_failed'=>0,
                    'status'=>0
                ];
                Db::name('wx_upload_shipping')->insert($data);
                return ['status'=>0,'msg'=>'稍后再试'];
            }
            $shipping_list = ['item_desc'=> $order['title']?$order['title']:self::getOrderTypeName($orderType)];
            //0普通快递 1到店自提 2同城配送 3自动发货 4在线卡密
            if(in_array($orderType,['restaurant_shop'])){
                //无需配送 订单
                $postdata['logistics_type'] = self::getWxLogisticsType();
            }else{
                if($order['freight_type'] === 0){
                    $shipping_list['tracking_no'] = $shippingInfo['express_no'];   //tracking_no 物流单号，物流快递发货时必填
                    $shipping_list['express_company'] = \app\common\Wxvideo::get_delivery_id($shippingInfo['express_com']);
                    $shipping_list['contact']['receiver_contact'] = substr($order['tel'], 0,3).'****'.substr($order['tel'],-4);
                    //contact 联系方式，当发货的物流公司为顺丰时，联系方式为必填，收件人或寄件人联系方式二选一
                }
                $postdata['logistics_type'] = self::getWxLogisticsType($order['freight_type']);//物流模式，发货方式枚举值：1、实体物流配送采用快递公司进行实体物流配送形式 2、同城配送 3、虚拟商品，虚拟商品，例如话费充值，点卡等，无实体配送形式 4、用户自提
            }
            $postdata['shipping_list'] = [$shipping_list];
            $postdata['order_key'] = [
                'order_number_type' => 2,
                'transaction_id'=>$wxpaylog['transaction_id']
//                'mchid' => $appinfo['wxpay_type'] == 0 ? $appinfo['wxpay_mchid'] : $appinfo['wxpay_sub_mchid'],
//                'out_trade_no'=>$order['ordernum']
            ];
            $postdata['delivery_mode'] = 1;
            $postdata['upload_time'] = date(DATE_RFC3339,time());
            $member = Db::name('member')->where('id',$order['mid'])->find();
            $postdata['payer'] = [
                'openid' => $member['wxopenid']
            ];
            $rs = \app\common\Wechat::uploadShippingInfo($aid,'wx',$postdata);
            if($rs['status'] == 1){
                Db::name('wxpay_log')->where('aid',$aid)->where('id',$wxpaylog['id'])->update(['is_upload_shipping_info'=>1]);
            }
            return $rs;
        }
    }

    //再次录入发货信息
    public static function retryUploadShipping()
    {
        $time = time();
        $list = Db::name('wx_upload_shipping')->where('status',0)->where('nexttime','<=',$time)->where('times_failed','<',3)
            ->select()->toArray();
        if($list){
            foreach ($list as $item){
                $order = Db::name($item['tablename'].'_order')->where('aid',$item['aid'])->where('ordernum',$item['ordernum'])->find();
                if($order['paytypeid'] == 2){
                    $rs = \app\common\Order::wxShipping($order['aid'],$order,$item['tablename']);
                    if($rs['status'] == 1){
                        Db::name('wx_upload_shipping')->where('id',$item['id'])->update(['status'=>1]);
                    }else{
                        Db::name('wx_upload_shipping')->where('id',$item['id'])->update(['nexttime'=>$time+60,'times_failed'=>$item['times_failed']+1]);
                    }
                }else{
                    Db::name('wx_upload_shipping')->where('id',$item['id'])->update(['status'=>-1]);
                }
            }
        }
    }

    /**
     * 微信物流模式
     * @param $freight_type  0普通快递 1到店自提 2同城配送 3自动发货 4在线卡密 5门店配送
     * @return void
     */
    public static function getWxLogisticsType($freight_type=''){
        //物流模式，发货方式枚举值：1、实体物流配送采用快递公司进行实体物流配送形式 2、同城配送 3、虚拟商品，虚拟商品，例如话费充值，点卡等，无实体配送形式 4、用户自提
        if($freight_type === 0){
            return 1;
        }else if($freight_type == 1){
            return 4;
        }else if($freight_type == 2){
            return 2;
        }else if($freight_type == 3){
            return 3;
        }else if($freight_type == 4){
            return 3;
        }
        return 3;
    }


    public static function getOrderTypeName($orderType)
    {
        $typeName = '订单';
        $orderType = str_replace('_order','',$orderType);
        if($orderType == 'shop'){
            $typeName = '商城订单';
        }elseif($orderType == 'recharge'){
            $typeName = '充值订单';
        }elseif($orderType == 'miandan'){
            $typeName = '买单订单';
        }elseif($orderType == 'scoreshop'){
            $typeName = t('积分').'兑换订单';
        }elseif($orderType == 'seckill'){
            $typeName = '秒杀订单';
        }elseif($orderType == 'collage'){
            $typeName = '拼团订单';
        }elseif($orderType == 'coupon'){
            $typeName = t('优惠券').'订单';
        }elseif($orderType == 'cycle'){
            $typeName = '周期购订单';
        }elseif($orderType == 'hbtk'){
            $typeName = '拓客订单';
        }elseif($orderType == 'kanjia'){
            $typeName = '砍价订单';
        }elseif($orderType == 'kecheng'){
            $typeName = '知识付费订单';
        }elseif($orderType == 'paotui'){
            $typeName = '跑腿订单';
        }elseif($orderType == 'restaurant_booking'){
            $typeName = '预定订单';
        }elseif($orderType == 'restaurant_shop'){
            $typeName = '点餐订单';
        }elseif($orderType == 'restaurant_takeaway'){
            $typeName = '外卖订单';
        }elseif($orderType == 'yuyue'){
            $typeName = '预约服务订单';
        }elseif($orderType == 'form'){
            $typeName = '表单订单';
        }elseif($orderType == 'member_levelup'){
            $typeName = t('会员').'升级';
        }elseif($orderType == 'designerpage'){
            $typeName = '页面';
        }

        return $typeName;
    }

    /**
     * 通过快递名字查询微信物流公司编码
     * @param $aid
     * @param $express_com
     * @return void ‘STO’
     */
    public static function getWxExpressCompany($aid,$express_com){
        $rs = \app\common\Wechat::get_delivery_list($aid);
        if($rs['status'] == 1) {
            $srs = collect($rs['delivery_list'])->where('delivery_name','=',$express_com)->first();
            return $srs['delivery_id'];
        }
    }

    /**
     * @param $aid
     * @param $orderid
     * @param $order
     * @param $mid
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function collectCheck($aid,$orderid=0,$order=[],$mid=0)
    {
        if(empty($order))
            $order = Db::name('shop_order')->where('aid',$aid)->where('mid',$mid)->where('id',$orderid)->find();
        else
            $orderid = $order['id'];

        if(!$order || ($order['status']!=2) || $order['paytypeid']==4){
            return ['status'=>0,'msg'=>'订单状态不符合收货要求'];
        }

        if(getcustom('product_collect_time')){
            //查询可确认收货时间
            $shopset = Db::name('shop_sysset')->where('aid',$aid)->field('ordercollect_time')->find();
            $start_time = time()-$shopset['ordercollect_time']*86400;
            if($order['send_time']>$start_time){
                return ['status'=>0,'msg'=>'订单发货后'.$shopset['ordercollect_time'].'天之后才可点击确认收货'];
            }
        }

        $refundOrder = Db::name('shop_refund_order')->where('refund_status','in',[1,4])->where('aid',$aid)->where('mid',$mid)->where('orderid',$orderid)->count();
        if($refundOrder){
            return ['status'=>0,'msg'=>'有正在进行的退款，无法确认收货'];
        }
        if($order['balance_price'] > 0 && $order['balance_pay_status']==0)
            return ['status'=>0,'msg'=>'请先支付尾款'];

        return ['status'=>1,'msg'=>'ok'];
    }

    public static function teamYejiManage($aid,$member){
        if(getcustom('yx_team_yeji_manage')){
            //团队管理奖
//            Db::startTrans();
//            dump($member);
            if(empty($member['path'])) return false;
            $set = Db::name('team_yeji_manage_set')->where('aid',$aid)->where('status',1)->find();
//            dump(Db::getLastSql());
//            dump($set);
            if($set['status'] != 1) return false;
            $config = json_decode($set['config_data'],true);
            if(empty($config)) return false;
            $levelids = array_keys($config);

            //查询所有父级
            $parentList = \app\common\Member::getParentsByPath($aid,$member['path'],[['levelid','in',$levelids]]);
            if(empty($parentList)) return false;
//            dump($parentList);

            foreach ($parentList as $parent){
                $configLevel = $config[$parent['levelid']];
//                dump($parent['id'].'-'.$parent['nickname']);
//                dump($configLevel);
                if(empty($configLevel)) continue;
                //直推团队
                $children1 = Db::name('member')->where('aid',$aid)->where('pid',$parent['id'])->column('id');
                if(empty($children1)) continue;
                //排除已发放
                $logmids = Db::name('team_yeji_manage')->where('aid',$aid)->where('mid',$parent['id'])->column('from_mid');
                if($logmids){
                    foreach ($children1 as $k => $mid){
                        if(in_array($mid,$logmids)){
                            unset($children1[$k]);
                        }
                    }
                }

                if(count($children1) < $configLevel['teamNum']){
                    continue;
                }
                $commission = 0;
                $score = 0;
                $teamNum = 0;//满足条件的团队数量
                $from_mids = [];
                //任意直推N条线业绩满足条件即为成功
                foreach ($children1 as $k => $mid){
                    if($configLevel['levelNum'] > 1){
                        $childrenmids = \app\common\Member::getdownmids($aid,$mid,$configLevel['levelNum']-1);
                        if(empty($childrenmids)) continue;
                        $childrenmids = array_merge([$mid],$childrenmids);
                    }else{
                        $childrenmids = [$mid];
                    }
//                    dump($childrenmids);

                    $yejiwhere = [];
                    $yejiwhere[] = ['status','in','1,2,3'];
                    $yeji = Db::name('shop_order_goods')->where('aid',$aid)->where('mid','in',$childrenmids)->where($yejiwhere)->sum('real_totalprice');
//                    dump('$yeji:'.$yeji);
                    if($yeji >= $configLevel['yeji']){
                        //满足一个团队
                        $from_mids[] = $mid;
                        $teamNum++;
                        if($teamNum >= $configLevel['teamNum']) break;
                    }
                }
//                dump('$teamNum:'.$teamNum);

                //发奖
                if($teamNum >= $configLevel['teamNum']){
//                if($score > 0){
//                    \app\common\Member::addscore($aid,$parent['id'],$score,'团队管理奖励');
//                    Db::name('member')->where('aid',$set['aid'])->where('id',$parent['id'])->inc('day_give_score_total',$score)->update();
//                }
                    $commission += $configLevel['commission'];
                    if($commission > 0){
                        $commission_member = $commission/$configLevel['teamNum'];
                        foreach ($from_mids as $from_mid){
                            \app\common\Member::addcommission($aid,$parent['id'],$from_mid,$commission_member,'团队管理奖励');
                            Db::name('team_yeji_manage')->insert(['aid'=>$aid,'mid'=>$parent['id'],'from_mid'=>$from_mid,'score'=>$score,'commission'=>$commission_member,'createtime'=>time()]);
                        }
                        Db::name('member')->where('aid',$aid)->where('id',$parent['id'])->inc('team_yeji_manage_commission_total',$commission)->update();
                    }
                }
            }

//            Db::commit();
        }
    }
    /**
     * 所有参与活动的用户平均发放返现
     * aid 商家id
     * mid 会员id
     * cashback 购物返现活动
     * og 商品id
     * back_price_total 返现金额
     */   
     
    public static function cashbackMemerDo($aid,$mid,$cashback,$og,$back_price_total,$cash_type = 0){
        $pro_id = $og['proid'];
        $cashback_member = Db::name('cashback_member')->where('aid',$aid)->where(['cashback_id'=>$cashback['id'],'pro_id'=>$pro_id])->whereRaw('cashback_money_max > cashback_money or cashback_money_max <= 0')->select()->toArray();
        //平均返现
        //$member_num = count($cashback_member);
        $member_num = array_sum(array_column($cashback_member,'pro_num'));
        $av_back_price_one = round($back_price_total/$member_num,2);
        $over_back_price = 0;
        foreach($cashback_member as $k=>$v){
            $av_back_price = $v['pro_num'] * $av_back_price_one;
            //自定义发放
            if($cash_type == 1){
                \app\custom\OrderCustom::deal_first_cashback($aid,$v['mid'],$av_back_price,$og,$cashback,1);
            }else{
                if($v['back_type'] == 1 ){
                    $cashback_num = $v['cashback_money'];
                }else if($v['back_type'] == 2 ){
                    $cashback_num = $v['commission'];
                }else if($v['back_type'] == 3 ){
                    $cashback_num = $v['score'];
                }
                if($v['cashback_money_max'] > 0 &&  $v['cashback_money_max'] > $cashback_num){
                    //最大可追加金额
                    $cashback_money_max = $v['cashback_money_max'] - $cashback_num;
                    if($cashback_money_max < $av_back_price){
                        $over_price = $av_back_price - $cashback_money_max;
                        $av_back_price_tem = $av_back_price;
                        $av_back_price = $cashback_money_max;
                        $over_back_price += $over_price;
                    }
                }
                if($v['back_type'] == 1 ){
                    \app\common\Member::addmoney($aid,$v['mid'],$av_back_price,$cashback['name']);
                }
                if($v['back_type'] == 2){
                    \app\common\Member::addcommission($aid,$v['mid'],$mid,$av_back_price,$cashback['name']);
                }
                if($v['back_type'] == 3){
                    $av_back_price = round($av_back_price);
                    \app\common\Member::addscore($aid,$v['mid'],$av_back_price,$cashback['name']);
                }
                Db::name('cashback_member')->where('id',$v['id'])->inc('cashback_money',$av_back_price)->update();
                //写入发放日志
                \app\custom\OrderCustom::cashbackMemerDoLog($aid,$v['mid'],$cashback,$og,$av_back_price);
                if($av_back_price_tem){
                    $av_back_price = $av_back_price_tem;
                }
            }
            
            
        }
        if($over_back_price >0 ){
            $res = self::cashbackMemerDo($aid,$mid,$cashback,$og,$over_back_price,$cash_type);
        }
        return true;
    }
    /**
     * 所有参与活动的用户平均发放返现
     * aid 商家id
     * mid 会员id
     * cashback 购物返现活动
     * og 商品
     * back_price_total 返现数量
     */   
     
    public static function cashbackMemerDoLog($aid,$mid,$cashback,$og,$back_price_total){

        $cashback_member = [];                                            
        $cashback_member['aid'] = $aid;
        $cashback_member['mid'] = $mid;
        $cashback_member['cashback_id'] = $cashback['id'];
        $cashback_member['pro_id'] = $og['proid'];
        if($cashback['back_type'] == 1 ){
            $cashback_member['cashback_money'] = $back_price_total;
        }else if($cashback['back_type'] == 2 ){
            $cashback_member['commission'] = $back_price_total;
        }else if($cashback['back_type'] == 3 ){
            $cashback_member['score'] = $back_price_total;
        }
        
        $cashback_member['back_type']          = $cashback['back_type'];
        $cashback_member['create_time'] = time();
        $insert = Db::name('cashback_member_log')->insert($cashback_member);
        return $insert;
    }
}
